Access ASP.NET Web API from Blazor razor page.

Razor Page

@page "/fetchdata"
@using System.Net.Http
@inject HttpClient Http

@if (products == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>ItemId</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var product in products)
            {
                <tr>
                    <td>@product.ItemId</td>
                    <td>@product.Name</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {

    class Product
    {
        public int ItemId { get; set; }
        public string Name { get; set; }
    }

    private Product[] products;

    protected override async Task OnInitializedAsync()
    {   
        products = await Http.GetJsonAsync<Product[]>("https://mywebapi.azurewebsites.net/api/product");
    }

}

Sources:

https://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-5.0

Last modified: November 24, 2020

Author

Comments

Write a Reply or Comment