Aspnetcore: HttpClient inject isn't working in Blazor 0.8

Created on 6 Feb 2019  路  1Comment  路  Source: dotnet/aspnetcore

Hi

I have created a new blazor component and tried to call get data from json file.

@function {
        protected override async Task OnInitAsync()
        {
           data = await Http.GetJsonAsync<GridItem[]>("sample-data/data.json");
        }
}

And got this error:

Uncaught (in promise) Error: System.InvalidOperationException: Cannot provide a value for property 'Http' on type 'BlazorGrid.App.Components.GridComponent'. There is no registered service of type 'System.Net.Http.HttpClient'.
   at Microsoft.JSInterop.DotNetDispatcher.InvokeSynchronously(String assemblyName, String methodIdentifier, Object targetInstance, String argsJson)
   at Microsoft.JSInterop.DotNetDispatcher.BeginInvoke(String callId, String assemblyName, String methodIdentifier, Int64 dotNetObjectId, String argsJson)
    at endInvokeDotNetFromJS (components.server.js:23)
    at components.server.js:23
    at new Promise (<anonymous>)
    at e.beginInvokeJSFromDotNet (components.server.js:23)
    at components.server.js:16
    at Array.forEach (<anonymous>)
    at e.invokeClientMethod (components.server.js:16)
    at e.processIncomingData (components.server.js:16)
    at e.connection.onreceive (components.server.js:16)
    at WebSocket.i.onmessage (components.server.js:16)

What's wrong here?

This is working in Blazor 0.7, but not working in Blazor 0.8

area-blazor

Most helpful comment

Hi @thainbreese,

It looks like your app is actually setup to use ASP.NET Core Razor Components instead of Blazor. Razor Components apps use the components.server.js script, but for Blazor you use components.webassemlby.js. Blazor Apps register a preconfigured HttpClient as a service that is available through dependency injection, but Razor Component apps do not.

In a Razor Components app you can just create new HttpClient instances, or if you want, you can register HttpClient as a service yourself. See https://github.com/Suchiman/BlazorDualMode for an example of how to do this.

I hope this helps!

>All comments

Hi @thainbreese,

It looks like your app is actually setup to use ASP.NET Core Razor Components instead of Blazor. Razor Components apps use the components.server.js script, but for Blazor you use components.webassemlby.js. Blazor Apps register a preconfigured HttpClient as a service that is available through dependency injection, but Razor Component apps do not.

In a Razor Components app you can just create new HttpClient instances, or if you want, you can register HttpClient as a service yourself. See https://github.com/Suchiman/BlazorDualMode for an example of how to do this.

I hope this helps!

Was this page helpful?
0 / 5 - 0 ratings