@inject HttpClient Http does not work on Blazor server application

Thursday, September 20, 2018 / mcchu28


The following code to  inject http service does not seem to work on a Blazor Server application.

@inject HttpClient Http

Even the default project from Visual Studio does not use HTTP injection. I am not sure if this is a change from the client side blazor, but I presume so.

Instead, they inject a custom service class:

@inject WeatherForecastService ForecastService

protected override async Task OnParametersSetAsync()
    {
        forecasts = await ForecastService.GetForecastAsync(StartDate);
    }


So the default project override the app method as follow.

    public class DefaultWeatherForecastService : WeatherForecastService
    {

        public override Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)


So the above example just call the server code to retrieve data from a file.

An example of calling an API through server code can be found here:
Probably you won't be using custom class IHttpApiClientRequestBuilderFactory but rather the HttpClient class.

[New Update Sep. 14, 2018]
At the bottom of this github issue, you will find Dan Roth's answer that you can add HttpClient to the server project. I will have to try this.

[New Update Sep. 20, 2018]
@robertmclaws The HttpClient uses JS interop to call into the fetch API (BrowserHttpMessageHandler). We don't introduce a new cookie container.

I also found on this thread https://github.com/aspnet/Blazor/issues/1115:
It talks about leverage the API client generation work planned for ASP.NET Core 2.2 to enable strongly typed API calls.