Published:

Blazor WebAssembly - HTTP POST Request Examples

Below is a quick set of examples to show how to send HTTP POST requests from ASP.NET Core Blazor WebAssembly to a backend API with the HttpClient class.

You can see all of the below examples running on GitHub Pages at https://cornflourblue.github.io/blazor-webassembly-http-post-request-examples.

The source code for the Blazor POST requests project is available at https://github.com/cornflourblue/blazor-webassembly-http-post-request-examples.

Other HTTP examples available:


Simple POST request with a JSON body and response type <Article>

This sends an HTTP POST request to the Reqres api which is a fake online REST api that includes a generic /api/<resource> route that responds to POST requests for any <resource> with the contents of the post body and a dynamic id property. This example sends a new article in the postBody to the /api/articles route and then converts the response to an Article object and assigns it to the blazor component property article so it can be displayed in the component template.

private Article article;

protected override async Task OnInitializedAsync()
{
    var postBody = new { Title = "Blazor POST Request Example" };
    using var response = await HttpClient.PostAsJsonAsync("https://reqres.in/api/articles", postBody);

    // convert response data to Article object
    article = await response.Content.ReadFromJsonAsync<Article>();
}

Blazor component code at https://github.com/cornflourblue/blazor-webassembly-http-post-request-examples/blob/master/Components/PostRequest.razor


POST request with a dynamic response type

This sends the same POST 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 string articleId;

protected override async Task OnInitializedAsync()
{
    var postBody = new { Title = "Blazor POST Request Example" };
    using var response = await HttpClient.PostAsJsonAsync("https://reqres.in/api/articles", postBody);

    // convert response data to JsonElement which can handle any JSON data
    var data = await response.Content.ReadFromJsonAsync<JsonElement>();

    // get id property from JSON response data
    articleId = data.GetProperty("id").GetString();
}

Blazor component code at https://github.com/cornflourblue/blazor-webassembly-http-post-request-examples/blob/master/Components/PostRequestDynamicResponse.razor


POST request with error handling

This sends a POST 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 Article article;
private string errorMessage;

protected override async Task OnInitializedAsync()
{
    var postBody = new { Title = "Blazor POST Request Example" };
    using var response = await HttpClient.PostAsJsonAsync("https://reqres.in/invalid-url", postBody);

    if (!response.IsSuccessStatusCode)
    {
        // set error message for display, log to console and return
        errorMessage = response.ReasonPhrase;
        Console.WriteLine($"There was an error! {errorMessage}");
        return;
    }

    // convert response data to Article object
    article = await response.Content.ReadFromJsonAsync<Article>();
}

Blazor component code at https://github.com/cornflourblue/blazor-webassembly-http-post-request-examples/blob/master/Components/PostRequestErrorHandling.razor


POST request with headers set

This sends the same POST 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 set the request body request.Content manually. It isn't possible to set headers using the above PostAsJsonAsync() extension method.

private Article article;

protected override async Task OnInitializedAsync()
{
    // create request object
    var request = new HttpRequestMessage(HttpMethod.Post, "https://reqres.in/api/articles");

    // set request body
    var postBody = new { Title = "Blazor POST Request Example" };
    request.Content = new StringContent(JsonSerializer.Serialize(postBody), Encoding.UTF8, "application/json");

    // 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 response = await HttpClient.SendAsync(request);

    // convert response data to Article object
    article = await response.Content.ReadFromJsonAsync<Article>();
}

Blazor component code at https://github.com/cornflourblue/blazor-webassembly-http-post-request-examples/blob/master/Components/PostRequestSetHeaders.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();
        }
    }
}

 

Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.

 


Supported by