Live Chat Icon For mobile
Live Chat Icon

Blazor FAQ - Web API

Find answers for the most frequently asked questions
Expand All Collapse All

The background long-running tasks are cancelled by using the CancellationToken object in Blazor. If an application downloads the data to render in view and then you navigate to another page, the CancellationToken cancels the download by using the Cancel() method. Call the Cancel()  method by using the Dispose() method to cancel the background running task.

In the following example, the background running task in the FetchData.razor component is cancelled when a user navigates to other pages in Blazor.
[FetchData.razor]

@page "/fetchdata" 
<PageTitle>Weather forecast</PageTitle> 
@using BlazorServerApp.Data 
@using System.Threading 
@implements IDisposable 
@using System.Net.Http 
@inject WeatherForecastService ForecastService 

<h1>Weather forecast</h1> 
<p>This component demonstrates fetching data from a service.</p> 
@if (forecasts == null) 
{ 
    <p><em>Loading...</em></p> 
} 
else 
{ 
    <table class="table"> 
        <thead> 
            <tr> 
                <th>Date</th> 
                <th>Temp. (C)</th> 
                <th>Temp. (F)</th> 
                <th>Summary</th> 
            </tr> 
        </thead> 
        <tbody> 
            @foreach (var forecast in forecasts) 
            { 
                <tr> 
                    <td>@forecast.Date.ToShortDateString()</td> 
                    <td>@forecast.TemperatureC</td> 
                    <td>@forecast.TemperatureF</td> 
                    <td>@forecast.Summary</td> 
                </tr> 
            } 
        </tbody> 
    </table> 
} 

@code { 
    private WeatherForecast[]? forecasts; 
    private readonly HttpClient httpClient = new HttpClient(); 
    private CancellationTokenSource? cancellationToken; 
    protected override async Task OnInitializedAsync () 
    { 
        cancellationToken = new CancellationTokenSource(); 
        try 
        { 
            forecasts = await httpClient.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json", cancellationToken.Token); 
        } 
        catch (OperationCanceledException) 
        { 
            // Task was cancelled 
        } 
    } 

    public void Dispose () 
    { 
        cancellationToken?.Cancel(); 
        cancellationToken?.Dispose(); 
    } 
} 

Refer to this documentation for more details.

Permalink

To read a JSON file in Blazor WebAssembly, you can utilize the HttpClient class along with the GetFromJsonAsync() method.  

Follow these steps to achieve that: 

To proceed, create or load a JSON file in the wwwroot folder. As an example, I have created a basic employee.json file and will read its values within a Razor component. 

[wwwroot/employee.json]

[{"id": "emp1"}, {"id": "emp2"}, {"id": "emp3"}]

[Index.razor]

@page "/"
@inject HttpClient Http

@if (employees == null)
{
    <p>Loading...</p>
}
else
{
    @foreach (var employee in employees) 
    { 
        <p>Employee ID: @employee.Id</p>
    }
}


@code {
    private Employee[] employees;

    protected override async Task OnInitializedAsync()
    {
        employees = await Http.GetFromJsonAsync<Employee[]>("employee.json");
    }

    public class Employee
    {
        public string Id { get; set; }
    }
}

Refer to this documentation for more details.

Permalink

In Blazor WebAssembly, a JSON response can be parsed by using the GetFromJsonAsync() method of HTTPClient. Get the JSON response through a Web API call and parse it using the GetFromJsonAsync() method. Use the following code to parse a JSON response in Blazor WebAssembly.

@inject HttpClient Http 
 
@code { 
    private BlazorData[] blazorData; 
    protected override async Task OnInitializedAsync() 
    { 
        // parses JSON response. 
        blazorData = await Http.GetFromJsonAsync<BlazorData[]>("api/blazorData"); 
    } 
} 

Refer to this documentation for more details.

Permalink

As opposed to how session cookies work, when opening a page in a new tab or window, a new session occurs with the browsing context. To access the browser sessionStorage in Blazor apps, write custom

code or use a third-party package. The accessed data can be stored in localStorage and sessionStorage. Know that localStorage is scoped to the user’s browser. If the user reloads the page or closes and reopens the browser, the state persists. Session storage is similar to local storage, but data in the session storage will be cleared after the session.

Install the Blazored.SessionStorage Nuget package in the NuGet package manager to store the session data in Blazor. Add the Blazored SessionStorage configuration to the WebAssembly app.

[Program.cs]

using Blazored.SessionStorage; 

. . . 
. . . 

            . . . 
            . . . 

            builder.Services.AddBlazoredSessionStorage(); 

[Index.razor]

@page "/" 

@inject Blazored.SessionStorage.ISessionStorageService sessionStorage 

<h2>@Name</h2> 

<button class="btn btn-primary" @onclick="Clear">Clear Session</button> 

@code { 
    public string Name; 
    protected override async Task OnInitializedAsync () 
    { 
        await sessionStorage.SetItemAsync("ID", "20019"); 
        await sessionStorage.SetItemAsync("Name", "John Smith"); 
        Name = "ID: " + await sessionStorage.GetItemAsync<string>("ID") + "Name : " + await sessionStorage.GetItemAsync<string>("Name"); 
    } 
    public async void Clear () 
    { 
        //this will clear the session data 
        await sessionStorage.ClearAsync(); 
    } 
} 
Permalink

You can read static files by creating HttpClient Get calls. The GetStringAsync method sends a request to the specific URI and returns the response body as a string in an async operation. 

@inject HttpClient Http

@code {

    protected override async Task OnInitializedAsync()
    {
        var content = await Http.GetStringAsync(request Uri);

    }
}

If you can read local file, you will use ReadAsync() and  Encoding.UTF8.GetString() methods. Here is an example:

@page "/read localfile" 
<InputFile OnChange="@HandleFileSelection" /> 
<button @onclick="ReadFile">Read File</button> 
@if (!string.IsNullOrEmpty(fileContent)) 
{ 
    <div>@fileContent</div> 
} 

@code { 
    private IBrowserFile? file; 
    private string? fileContent; 
    private void HandleFileSelection(InputFileChangeEventArgs e) 
    { 
        file = e.File; 
    } 
    private async Task ReadFile() 
    { 
        if (file != null) 
        { 
            var stream = file.OpenReadStream(); 
            var buffer = new byte[file.Size]; 
            await stream.ReadAsync(buffer, 0, (int)file.Size); 
            fileContent = System.Text.Encoding.UTF8.GetString(buffer); 
        } 
    } 
} 

Note: The project mentioned above is designed for reading local text format documents. 

View Sample in GitHub  

Permalink

In the Blazor client-side application, you can call the web APIs using HttpClient service. In the following code, the GetData API is called on button click event. The GetFromJsonAsync method is used to get the parsed Json data.

@inject HttpClient Httpclient

<button @onclick="@GetData">Get Data</button>

@code {

    private async Task GetData()
    {
        await Httpclient.GetFromJsonAsync<T>("api/GetData");
    }
}
Permalink

First to access browser Session Storage in Blazor apps, write a custom code or use a third party package. The accessed data can be stored in the Local Storage and Session Storage.  The Local Storage is scoped to the user’s browser. If the user reloads the page or closes and reopens the browser, the state persists. Session storage is similar to Local Storage but the data in the session storage will be cleared after the session. 

Use the Blazored.SessionStorage package to store the session data in Blazor. For this install the package and add the service to the application.

[Program.cs] 

using Blazored.SessionStorage; 
…
builder.Services.AddBlazoredSessionStorage();

[index.razor]

@page "/"
@inject Blazored.SessionStorage.ISessionStorageService sessionStorage

<h2>@Name</h2>
<button @onclick="Clear">Clear Session</button>
@code {
    public string Name;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await sessionStorage.SetItemAsync("ID", "20019");
        await sessionStorage.SetItemAsync("Name", "John Smith");
        Name = "ID: " + await sessionStorage.GetItemAsync<string>("ID") + "Name : " + await sessionStorage.GetItemAsync<string>("Name");
    }
   public async void Clear()
   { 
    //this will clear the session data 
     await sessionStorage.ClearAsync();
    }
}
Permalink

To add Google Maps to a Blazor application, use the Google Maps API script. To initialize Google Maps in Blazor we need to use a JavaScript interop. 

Add the following scripts to ~/Pages/_Layout.cshtml /_Host.cshtml for Server Blazor app or ~/wwwroot/index.html for Blazor WebAssembly app. 

[_Host.cshtml/_Layout.cshtml/index.html] 

<head> 
      <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"></script> 
</head> 

[Script.js]

function initialize() { 
    var latlng = new google.maps.LatLng(40.716948, -74.003563); 
    var options = { 
        zoom: 14, center: latlng, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    var map = new google.maps.Map(document.getElementById("map"), options); 
} 

[index.razor]

@page "/" 
@inject IJSRuntime JSRuntime 

<h1>Display Google Map</h1> 
<div id="map" style="height:500px;width:100%;"> 
</div> 

@code { 
    protected override async Task OnAfterRenderAsync ( bool firstRender ) 
    { 
        if (firstRender) 
        { 
            await JSRuntime.InvokeVoidAsync("initialize", null); 
        } 
    } 
}

In the above example, Google Maps is initialized in the OnAfterRenderAsync life cycle method. By invoking it using a JavaScript interop, this will initialize Google Map API when the page is rendered. 

View Sample in GitHub 

Note: If you’d like to know how to render Google Maps in Syncfusion Blazor Map, take a look at our  documentation section

Permalink

While making an API call, create and run an asynchronous task with the Run method to notify the wait using a spinner. The completion of the task can be notified using the  CompletedTask property.

[index.razor]

@page "/" 

<style> 
    .loader { 
        border: 5px solid #f3f3f3; 
        border-radius: 50%; 
        border-top: 5px solid #f58205; 
        width: 30px; 
        height: 30px; 
        -webkit-animation: spin 2s linear infinite; /* Safari */ 
        animation: spin 2s linear infinite; 
    } 
    /* Safari */ 
    @@-webkit-keyframes spin { 
        0% { 
            -webkit-transform: rotate(0deg); 
        } 
        100% { 
            -webkit-transform: rotate(360deg); 
        } 
    } 
    @@keyframes spin { 
        0% { 
            transform: rotate(0deg); 
        } 
        100% { 
            transform: rotate(360deg); 
        } 
    } 
</style> 

<h1>Counter</h1> 

<p> 
    Current count: <div class="@(spin ? "loader" : "")"> @(spin ? "" : currentCount.ToString()) </div> 
</p> 

<button class="btn btn-primary" @onclick="@IncrementCount"> Click me </button> 
<button class="btn btn-dark" @onclick="@AsyncCallback"> API Callback </button> 

@code { 
    int currentCount = 0; 
    bool spin = false; 
    void IncrementCount () 
    { 
        currentCount++; 
    } 
    async Task AsyncCallback () 
    { 
        spin = true; 
        await Task.Run(() => APICallback());  //<==check this!!! 
        currentCount++; 
        spin = false; 
        await Task.CompletedTask; 
    } 

    void APICallback () => Task.Delay(1500).Wait(); 
}

Output:

View Sample in GitHub

Permalink

An HTTP Delete request can be sent to delete a resource from the API server using the DeleteAsync () method provided by the HttpClient class.

Razor

@page "/employee/delete"
@inject HttpClient Http
@inject NavigationManager Navigate
.. .. .. .. .. .. 
.. .. .. .. .. ..

@code {
    Employee emp = new Employee();
    protected async Task Delete()
    {
        await Http.DeleteAsync("api/Employee/Delete/" + Convert.ToInt32(empID));
        Navigate.NavigateTo("/employee");
    }
}

Web API

[HttpDelete]
[Route("api/Employee/Delete/{id}")]
public void Delete(int id)	
{
    employee.DeleteEmployee(id);
}

Reference link: https://medium.freecodecamp.org/how-to-create-an-application-using-blazor-and-entity-framework-core-1c1679d87c7e

Permalink

An HTTP GET request can be sent to get a resource from the API server using the GetJsonAsync() method provided by the HttpClient class.

CSHTML

@page "/employee"
@inject HttpClient Http

.. .. .. .. .. .. 
.. .. .. .. .. ..

@code {
        Employee[] empList;

        protected override async Task OnInitializedAsync()
        {
            empList = await Http.GetJsonAsync<Employee[]>("/api/Employee/Index");
        }
}

Web API

[HttpGet]
[Route("api/Employee/Index")]
public IEnumerable<Employee> Index()
{
    return employee.GetAllEmployees();
}

Reference link: https://medium.freecodecamp.org/how-to-create-an-application-using-blazor-and-entity-framework-core-1c1679d87c7e

Permalink

An HTTP POST request can be sent to add new data in the API server using the SendJsonAsync () method provided by the HttpClient class.

Razor

@page "/employee/add"
@inject HttpClient Http

.. .. .. .. .. .. 
.. .. .. .. .. ..

@code {
    Employee emp = new Employee();
    protected async Task CreateEmployee()
    {
        await Http.SendJsonAsync(HttpMethod.Post, "/api/Employee/Create", emp);
    }
}

Web API

[Route("api/Employee/Create")]
public void Create([FromBody] Employee employee)
{
    if (ModelState.IsValid)
        this.employee.AddEmployee(employee);
}

Reference link:

https://medium.freecodecamp.org/how-to-create-an-application-using-blazor-and-entity-framework-core-1c1679d87c7e

Permalink

The HTTP PUT method is used to completely replace a resource on the API server. We can use the HttpClient to send a PUT request to an API server using the SendJsonAsync () method. 

CSHTML       

@page "/employee/edit"
@inject HttpClient Http

.. .. .. .. .. .. 
.. .. .. .. .. ..

@code {
    Employee emp = new Employee();
    protected async Task UpdateEmployee()
    {
        await Http.SendJsonAsync(HttpMethod.Put, "api/Employee/Edit", emp);
        UriHelper.NavigateTo("/employee");

    }
}

Web API

[HttpPut]
[Route("api/Employee/Edit")]
public void Edit([FromBody]Employee employee)
{
    if (ModelState.IsValid)
        this.employee.UpdateEmployee(employee);
}

Reference link:

https://medium.freecodecamp.org/how-to-create-an-application-using-blazor-and-entity-framework-core-1c1679d87c7e

Permalink

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.