Loading, please wait...

A to Z Full Forms and Acronyms

How to use Sessions in Blazor Application

In this article, we will see how to store data and read the data from Sessions in Blazor.

Session Storage is scoped to the browser tab. If the user reloads the tab, the state persists. If the user closes the tab or the browser, the state is lost. If the user opens multiple browser tabs, each tab has its independent version of the data.

Blazor is fundamentally incompatible with the concept of traditional server-side sessions, especially in the client-side or WebAssembly hosting model where there is no server-side, to begin with. Even in the "server-side" hosting model, though, communication with the server is over WebSocket. There's only one initial request. Server-side sessions require a cookie which must be sent to the client when the session is established, which means the only point you could do that is on the first load. Afterward, there are no further requests, and thus no opportunity to establish a session.

The Article will give you details on how to maintain session state in a Blazor app to the closest thing to traditional server-side sessions.

First Create a sample application to test the below steps along with me.

In the default sample application of the Blazor Server app, we need to add the first NuGet Package “Blazored.SessionStorage” by Chris Sainty it’s open-source and licensed by MIT so we can use this for our commercial applications too.

After installing this package, we just need to go into a startup.cs class file and register its service with the below code in ConfigServices() method:

Services.AddBlazoredSessionStorage();

Or check the below image:

Now, we are all set to use this session storage service.

We can use the below functions from the session storage service to read or set the values.

  1. SetItemAsync():

    With this SetItemAsync function, we can store any type of value asynchronously for the current session with two function parameters “ItemName” and <T> Value.

  2. GetItemAsync();
    We use this function from the same service to read any existing value from the current session, we just need to pass the first parameter of the ItemName which needs to be used.

How to set the value?

Inject the dependency and you’ll get its instance at run time and just use the same variable for calling the SetItemAsync() function with the respected parameters.

How to get the value?

In the same way, I just declared a dependency injected variable of session storage service:

@inject Blazored.SessionStorage.ISessionStorageService sessionStorage

And now in an async function, I returned a task with await statement for GetItemAsync() function using the item name which needs to use.

@code {
    int count;
    public async Task ReadCounter()
    {
        count = await sessionStorage.GetItemAsync<int>("count");
    }
}

We can call this function on any event of component life cycle or any custom event like button click and it’ll update its binding locations:

<p>
    @if(count!=0)
    {
        <label>@count</label>
    }
    else
    {
        <label>No Data !</label>
    }
</p>

In my sample I have added one more component “SessionValue.razor” with routing value as “/value” and I have added an HTML button in my page DOM to call the function which will read the “count” value from session storage service.

Just build the application and get its preview in your browser.

Open the counter component click the “click me” button for incrementing the counter’s local value and it’ll update the value of the session for the same item name “count”.

Now for testing whether it’s stored in session storage service properly or not we need to navigate on the “/value” component and now just call the function with the button click.

I hope you’ll get your value. This value will not be available for other sessions or users.

A to Z Full Forms and Acronyms