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]

@using System.Threading
@implements IDisposable

// . . .
@code {
    private CancellationTokenSource cancellationToken = new CancellationTokenSource();

    protected override async Task OnInitializedAsync()
    {
        forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json", cancellationToken.Token);
    }

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

Refer to this documentation for more details.

Permalink

Use the HttpClient class with the GetFromJsonAsync() method to read a JSON file in Blazor WebAssembly. Follow these steps to read the JSON file.

Create or load a JSON file under the wwwroot folder. For example, here we have created a simple employee.json file and read its values in 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;
. . .
. . .

public class Program
    {
        public static async Task Main(string[] args)
        {
            . . .
            . . .

            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();
    }
}

Refer to the GitHub SessionStorage repository for more details.

Permalink

You can read static or local 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);

    }
}

Please refer to “HttpClient Class” for more details.

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 seesionStorage in Blazor apps, write a custom code or use a third party package. The accessed data can be stored in the localStorage and sessionStorage.  The 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 the 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.

[startup.cs]
using Blazored.SessionStorage;

public void ConfigureServices(IServiceCollection services)
{
         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();
    }
}

Reference link: https://github.com/blazored/SessionStorage

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/_Host.cshtml for Server Blazor app or ~/wwwroot/index.html for Blazor WebAssembly app.

[_Host.cshtml/index.html]

<head>
    <script src="~/script.js"></script>
    <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.

You can download the reference sample here.

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 Call Back </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:

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

Share on twitter
Share on facebook
Share on linkedin

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

Please submit your question and answer.