Share via

Error while using IJSRuntime or HttpClient in a separate .cs file in Blazor WebAssembly

langlang fang 1 Reputation point
2020-07-24T09:46:29.743+00:00

Error while using IJSRuntime or HttpClient in a seperate .cs file in Blazor WebAssembly!

I am testing a project with Blazor WebAssembly, in a Razor component, I can normally use the IJSRuntime or HttpClient , however, I hope to move those code to a separate file for better management, using dependency injection way. but as a result, program can run to the function but is failed to call a IJSRuntime or HttpClient function which works properly in Razor component. Could you let me know where I did is wrong? Thank you very much!
and this is my JavaScript code for browser data storage:
window.stateManager = {
set: function (key, str) {
window.localStorage[key] = str;
},
get: function (key) {
return window.localStorage[key];
},
getAll: function () {
return window.localStorage;
}
};

window.sessionManager = {
set: function (key, str) {
window.sessionStorage[key] = str;
},
get: function (key) {
return window.sessionStorage[key];
},
getAll: function () {
return window.sessionStorage;
}
};

Every time when run to the code, it gives error as below:
****…………GetLocalBufferValue!!!!!^^^^^System.ArgumentNullException: Value cannot be null.
Parameter name: jsRuntime
at Microsoft.JSInterop.JSRuntimeExtensions.InvokeAsync[TValue] (Microsoft.JSInterop.IJSRuntime jsRuntime, System.String identifier, System.Object[] args) <0x34a72c0 + 0x00014> in <filename unknown>:0
at EnergyManagePro.Client.BaseFiles.JSHelper.GetLocalBufferValue (System.String key) [0x00023] in C:\Users\Tony\source\repos\EnergyManagePro-200723\Client\BaseFiles\CBase.cs:100****

13528-%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE-20200724173558.png

Community Center | Not monitored
0 comments No comments

1 answer

Sort by: Most helpful
  1. Vahid Ghafarpour 23,600 Reputation points
    2023-09-18T18:21:46.3533333+00:00

    The error you're encountering, System.ArgumentNullException: Value cannot be null. Parameter name: jsRuntime, suggests that the IJSRuntime instance is not being properly injected into your separate class where you are trying to use it. To use IJSRuntime or HttpClient in a separate class in Blazor WebAssembly, you need to make sure you properly inject these services.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.