HTTP request in Blazor WebAssembly application

Keywords: ASP.NET http

In my previous article HTTP request in Blazor Server application, I introduced the related technologies of HTTP request in Blazor Server application. In Blazor Server App, you can access all. NET class libraries and components. However, if you create a Blazor WebAssembly application, your code will run in the browser sandbox of the client, and your choice will be limited to some extent. In this tutorial, I'll show you how to make HTTP requests in the Blazor WebAssembly application.

HttpClient overview in the Blazor WebAssembly application

The Blazor WebAssembly application invokes the Web API using the preset HttpClient service. This preset HttpClient uses the browser's Fetch API[2]   Implementation, there will be some limitations. HttpClient can also make API calls using the razor JSON helper or HttpRequestMessage object. By default, you can only send API call requests to the same origin server, but if the third-party API supports cross domain resource sharing (CORS), you can also call APIs on other servers.

The namespace System.Net.Http.Json provides extension methods for HttpClient that performs automatic serialization and deserialization using System.Text.Json. These extension methods send the request to a Web API URI and process the corresponding response. Common methods are:

  • GetFromJsonAsync: sends an HTTP GET request and parses the JSON response body into an object.

  • PostAsJsonAsync: sends the POST request to the specified URI and carries the information serialized as JSON in the request body   value.

  • PutAsJsonAsync: sends an HTTP PUT request containing JSON encoded content.

To understand how to use these methods with HttpClient, we need to create two projects. The first project is a Web API project that exposes a Web API to the client. The second project is the Blazor WebAssembly application, which sends HTTP requests to the Web API created in the first project.

Implement an ASP.NET Core Web API

In this section, we will implement a Web API that supports cross domain resource sharing (CORS) so that Blazor WebAssembly applications can call this API. Create a new Web API project in Visual Studio 2019   BlazorClientWebAPI. We will create a simple API to return the product list, so first create one in the project   Models   Folder and add the following   Product   Class.

Product.cs

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Next, create a   Controllers   Folder and add the following   ProductsController. The controller simply starts from   GetProducts   Method returns some simulated product data.

ProductsController.cs

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetProducts()
    {
        var products = new List<Product>()
        {
            new Product()
            {
                Id = 1,
                Name = "Wireless Mouse",
                Price = 29.99m
            },
            new Product()
            {
                Id = 2,
                Name = "HP Headphone",
                Price = 79.99m
            },
            new Product()
            {
                Id = 3,
                Name = "Sony Keyboard",
                Price = 119.99m
            }
        };
 
        return Ok(products);
    }
}

Now if you run the project and try to use URI s in your browser   api/products   By accessing the API, you should be able to see the product data returned in JSON format.

Enabling CORS in ASP.NET Core Web API

By default, browser security does not allow a web page to send requests to domains other than the domain that provides the web page. This constraint is called homology strategy. If we want Blazor WebAssembly applications or other client applications to use the above web APIs, we must enable cross domain resource sharing (CORS). open   Startup.cs   File, and in   ConfigureServices   Call in method   AddCors   method.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(policy =>
    {
        policy.AddPolicy("CorsPolicy", opt => opt
            .AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod());
    });
 
    services.AddControllers();
}

At the same time, in   Startup.cs   Document   Configure   Method.

app.UseCors("CorsPolicy");

For more information about CORS using asp.net core applications, see   <Enable Cross-Origin Requests (CORS) in ASP.NET Core>[3].

Implementing the Blazor WebAssembly application

Add a new Blazor WebAssembly application project to the same solution that created the above Web API project   BlazorClientWebAPIsDemo.

The first thing we need to ensure is that there are   System.Net.Http.Json   Reference to. If not, you can add the reference.

<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
   <PropertyGroup>
      <TargetFramework>net5.0</TargetFramework>
   </PropertyGroup>
   <ItemGroup>
      <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="5.0.1" />
      <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="5.0.1" PrivateAssets="all" />
      <PackageReference Include="System.Net.Http.Json" Version="5.0.0" />
   </ItemGroup>
</Project>

Next, we need to   Program.cs   The HttpClient service is configured in the file. Ensure that the base address of the Web API to be invoked from the Blazor WebAssembly application is provided.

Program.cs

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("#app");
 
    builder.Services.AddScoped(sp => new HttpClient
    {
        BaseAddress = new Uri("http://localhost:5000/api/")
    }); 
 
    await builder.Build().RunAsync();
}

In order to use the product API, we   Pages   Create a folder   Products.razor   Components. This view is very simple because it just iterates over the list of products and displays them using a simple HTML table.

Products.razor

@page "/products"
 
<h1>Products</h1>
 
@if (products == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in products)
            {
                <tr>
                    <td>@forecast.Id</td>
                    <td>@forecast.Name</td>
                    <td>@forecast.Price</td>
                </tr>
            }
        </tbody>
    </table>
}

Create a code behind file   Products.razor.cs, and the configured   HttpClient   Instance is injected into the class as a private member. Finally, use   GetFromJsonAsync   Method calls the product API.

Products.razor.cs

public partial class Products
{
    private List<Product> products;
 
    [Inject]
    private HttpClient Http { get; set; }
 
    protected override async Task OnInitializedAsync()
    {
        products = await Http.GetFromJsonAsync<List<Product>>("products");
    } 
}

You also need to create one in the blazor web assembly project   Product   Class to deserialize the results of the product API into a list of product objects.

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Run the project and you will see a page loaded with products from the back-end Web API.

Posted by pragma on Fri, 10 Sep 2021 19:17:05 -0700