Blazor WebAssembly - HTTP GET Request Examples
Below is a quick set of examples to show how to send HTTP GET requests from ASP.NET Core Blazor WebAssembly to a backend API.
You can see all of the below examples running on GitHub Pages at https://cornflourblue.github.io/blazor-webassembly-http-get-request-examples/.
The source code for the Blazor GET requests project is available at https://github.com/cornflourblue/blazor-webassembly-http-get-request-examples.
Other HTTP examples available:
- Blazor WebAssembly: POST
- Angular: GET, POST, PUT, DELETE
- React + Fetch: GET, POST, PUT, DELETE
- React + Axios: GET, POST, PUT, DELETE
- Vue + Fetch: GET, POST, PUT, DELETE
- Vue + Axios: GET, POST
- Axios: GET, POST, PUT, DELETE
- Fetch: GET, POST, PUT, DELETE
Simple GET request with a JSON body and strongly typed response <UsersResponse>
This sends an HTTP GET request to the Reqres api which is a fake online REST api that has an /api/users
route that returns an array of users along with metadata including the total
number of users. The GetFromJsonAsync()
extension method of the HttpClient
is called to send a request and convert the response into a UsersResponse
object which is assigned to the blazor component property response
so it can be rendered by the component template
private UsersResponse response;
protected override async Task OnInitializedAsync()
{
response = await HttpClient.GetFromJsonAsync<UsersResponse>("https://reqres.in/api/users");
}
Blazor component code at https://github.com/cornflourblue/blazor-webassembly-http-get-request-examples/blob/master/Components/GetRequest.razor
GET request with a dynamic response type
This sends the same GET request from Blazor using the HttpClient, but this example converts the response data to a JsonElement
object so it can handle any properties returned in the response.
private int? total;
protected override async Task OnInitializedAsync()
{
// convert response data to JsonElement which can handle any JSON data
var data = await HttpClient.GetFromJsonAsync<JsonElement>("https://reqres.in/api/users");
// get total property from JSON response data
total = data.GetProperty("total").GetInt32();
}
Blazor component code at https://github.com/cornflourblue/blazor-webassembly-http-get-request-examples/blob/master/Components/GetRequestDynamicResponse.razor
GET request with error handling
This sends a GET request from Blazor to an invalid url on the api then assigns the error message to the errorMessage
component property and logs the error to the console.
private UsersResponse response;
private string errorMessage;
protected override async Task OnInitializedAsync()
{
using var httpResponse = await HttpClient.GetAsync("https://reqres.in/invalid-url");
if (!httpResponse.IsSuccessStatusCode)
{
// set error message for display, log to console and return
errorMessage = httpResponse.ReasonPhrase;
Console.WriteLine($"There was an error! {errorMessage}");
return;
}
// convert http response data to UsersResponse object
response = await httpResponse.Content.ReadFromJsonAsync<UsersResponse>();
}
Blazor component code at https://github.com/cornflourblue/blazor-webassembly-http-get-request-examples/blob/master/Components/GetRequestErrorHandling.razor
GET request with headers set
This sends the same GET request again from Blazor with a couple of headers set, the HTTP Authorization
header and a custom header My-Custom-Header
.
In order to set HTTP headers you need to create an HttpRequestMessage
object and send it using the SendAsync()
method. It isn't possible to set headers using the above GetAsync()
and GetFromJsonAsync()
extension methods.
private UsersResponse response;
protected override async Task OnInitializedAsync()
{
// create request object
var request = new HttpRequestMessage(HttpMethod.Get, "https://reqres.in/api/users");
// add authorization header
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "my-token");
// add custom http header
request.Headers.Add("My-Custom-Header", "foobar");
// send request
using var httpResponse = await HttpClient.SendAsync(request);
// convert http response data to UsersResponse object
response = await httpResponse.Content.ReadFromJsonAsync<UsersResponse>();
}
Blazor component code at https://github.com/cornflourblue/blazor-webassembly-http-get-request-examples/blob/master/Components/GetRequestSetHeaders.razor
Prerequisites for making HTTP requests from Blazor WebAssembly
Before making HTTP requests from your Blazor app you need to do a couple of things.
1. Add the System.Net.Http.Json
NuGet package to your Blazor project file (.csproj
) like below on line 12
.
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<RazorLangVersion>3.0</RazorLangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="3.2.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="3.2.1" PrivateAssets="all" />
<PackageReference Include="System.Net.Http.Json" Version="3.2.1" />
</ItemGroup>
</Project>
2. Configure the HttpClient
for dependency injection in your Program.cs
file like below on line 17
.
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace BlazorApp
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
// configure http client
builder.Services.AddScoped(x => new HttpClient() { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
var host = builder.Build();
await host.RunAsync();
}
}
}
Need Some Blazor Help?
Search fiverr for freelance Blazor developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!