The Web Assembly Blazor HttpClient

The .NET Framework HttpClient class provides a means for managing requests and responses over HTTP from a resource identified by a URI. In Blazor WebAssembly, an implementation of the HttpClient is provided as a pre-configured service within Program.cs:

builder.Services.AddScoped(sp => new HttpClient { 
    BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) 
});

It is readily available to be injected anywhere within the client application without requiring any additional set-up steps or concerns over lifetime management.

Note

If your registration uses AddTransient as was the case with some older project templates, you are advised to register as a Scoped or Singleton service instead. In a Blazor WebAssembly app, scoped services act as singletons.

The version provided to Blazor WASM applications delegates requests to the browser's Fetch API. As such, it is restricted to making calls to the server of origin. If you need to access resources on a different domain, you can only do this using the browser-based HttpCient if the remote resource has enabled cross origin request sharing (CORS). Alternatively, you can use a server-side instance of HttpClient as a proxy, which is not subject to the same restrictions. In this scenario, your client app uses its Fetch-based HttpClient to call a server-side service that then uses the .NET HttpClient to make the request.

JSON Extension Methods

A collection of convenience extension methods on the HttpClient type have been provided to simplify the code required to work with JSON, which is the format that you are most likely to work with when using the HttpClient to call web services. These methods are defined in the System.Net.Http.Json package. Content being sent is serialised to JSON and properly encoded as UTF-8 with the appropriate content-type header. Responses are deserialised from JSON.

Method Description
GetFromJsonAsync andGetFromJsonAsync<T> Makes a GET request to the specified requestUri and attempts to serialise the response into the type represented by the T parameter or the Type parameter. You can see an example of this in the FetchData component in the standard Blazor WebAssembly project templates. There are 4 overloads for each of these methods. The ones that you are likely to use most often take a string or Uri representing the URL of the resource.
PostAsJsonAsync Makes a POST request to the specified requestUri, sending the value as part of the request body and returns an HttpResponseMessage. Overloads exist allowing you to specify the requestUri as a string or Uri, and to provide serialisation options and cancellation tokens.
PutAsJsonAsync Makes a PUT request to the specified requestUri, sending the content as part of the request body and returns an HttpResponseMessage. Overloads exist allowing you to specify the requestUri as a string or Uri, and to provide serialisation options and cancellation tokens.

If you are using HttpClient in situations other than directly within a Razor component, such as within a class library, these utility methods are not available by default. You need to install the System.Net.Http.Json package from Nuget and to add a using directive for System.Net.Http.Json.

Note: if you see samples that use methods without the As or From in the name, or are looking for a SendJsonAsync method, those were most likely based on an earlier preview of Blazor, where the JSON extension methods were first introduced.

Examples

The following example features in the standard project template for an ASP.NET hosted Blazor WebAssembly application. It is found in the FetchData component. The HttpClient service is injected into the component:

@inject HttpClient Http

It is used to call WeatherForecast controller's Get method using the GetFromJsonAsync<T> method, deserialising the response to an array of WeatherForecast instances:

@code {
    private WeatherForecast[]? forecasts;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
    }
}

Posting JSON

Any value that you pass the the PostAsJsonAsync method is automatically serialised to JSON. in this simple example, the type passed to the value parameter is an anonymous type:

@inject HttpClient Http
@code {
    var person = new { Name = "Mike", Location = "UK" };
    await Http.PostAsJsonAsync("/api/save", person);
}

Uploading a file

When uploading files in Blazor WebAssembly, you are more likely to work with the IBrowserFile type rather than JSON.

The InputFile component is used for uploading files in a Blazor WebAssembly application. It has an OnChange event that you can hook into to access the selected file(s). The selected file is represented by the File property of the InputFileChangeEventArgs that is passed to the OnChange event handler.

HTTP requests that contain file data must be encoded as multipart/form-data. The .NET type that acts as a container for such content is the MultipartFormDataContent class. When uploading the file, you pass the file data to an instance of MultipartFormDataContent and post that:

@inject HttpClient Http
@using System.Net.Http.Headers
<InputFile OnChange="UploadFile" />

@code {
    async Task UploadFile(InputFileChangeEventArgs e)
    {
        var file = e.File;
        using var content = new MultipartFormDataContent();
        var fileContent = new StreamContent(file.OpenReadStream(file.Size));
        if (!string.IsNullOrWhiteSpace(file.ContentType))
        {    
            fileContent.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
        }
        content.Add(content: fileContent, name: "\"uploads\"", fileName: file.Name);
        await Http.PostAsync("/upload", content);
    }
}
Last updated: 2/15/2023 9:01:56 AM

Latest Updates

© 2023 - 2024 - Mike Brind.
All rights reserved.
Contact me at Mike dot Brind at Outlook.com