Skip to content

J-Wachs/BlazorSessionStorage

Repository files navigation

Session storage service for Blazor applications

This service allows for storing and retrieving data to/from session storage in your Blazor application. The service allows to store/retrieve strings, integers and objects in either a server or client (browser) side session storage. The session storage 'survives' reloading the browser window.

Please note, this service cannot be used in WebAssembly.

The component has been developed in .NET 9.

Fully functional example project

This repo contains a project that is the actual service and a demo project, where you can see examples of using the session storage:

  • Counter example using client (browser) side session storage
  • Counter example using server side session storage
  • Data entry example using server side session storage

How does it work?

From time to time the need to store some data on the fly in a Blazor application araise. It could the Id of a shopping basket, an order number or something else. In ASP .NET it is easy to store this kind of temporary data in the Session object. Blazor does not have an equalment to ASP .NET's Session object.

In many application the workaround for this has been to add a service that can hold the values. This is typically done by adding a service scoped. Another method is to use the PersistentComponentState class. Both of these solutions has a drawback, and that is that when you reload the application in the browser, the stored data is lost. The reason for this is that the connection between the browser and the server is disconnected and a new connection is establiched. That is, a new circuit is established.

The implementation for client (browser) side session storage relies on the class ProtectedSessionStorage. This class will store your data in the browser's session storage. The information will be stored encrypted. To use this type of session storage in your project, minimal changes are needed. You just need to add the service in Program.cs.

The implementation for server side session storage requires that your project is set up for using ASP .NET sessions. This requires a number of additions to Program.cs. The data is stored in the HttpContext session object.

No matter if you select to use server or client side session storage, please note that you must consider the amount of data that you want to store. Keep the stored data to a reasonable size.

In the included demo project, the two variants of session storage (server or client) is implemented as 'Keyed services' allowing to demo the two types in the same project without changes and recompile.

Installation instructions

Getting and trying out the session storage service

Download the repo and open the demo project in Visual Studio. Play around with the demo.

Setting up your own project to use the session storage service

Depending on your application and needs, you can either use just one of the session storage types or, as in the demo project, use both.

To use only the browser session storage, all you need is to add the service to Program.cs:

...
// This is needed for browser side session storage:
builder.Services.AddScoped<ISessionStorage, BrowserSessionStorage>();
// End This is needed for browser side session storage:
...

To use only the server side session storage, you will need to add the following to Program.cs (see in the demo project for the correct places to add entries):

...
// This is needed for server side session storage:
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    // Make sure this is allowed for your application!
    options.Cookie.IsEssential = true;
    options.IdleTimeout = new TimeSpan(0, 0, 3, 0);
});
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ISessionStorage, ServerSessionStorage>();
// End This is needed for server side session storage
...

After the 'builder.Build()' statement:

...

// This is needed for server side session storage:
app.UseSession();
app.Use(async delegate (HttpContext context, Func<Task> next)
{
    // Workaround to be able to set data in session
    var tempKey = Guid.NewGuid().ToString();
    context.Session.Set(tempKey, Array.Empty<byte>());
    context.Session.Remove(tempKey);
    await next();
});
// End This is needed for server side session storage
...

Please note that the above code (app.Use()...) is a workaround that must be added for the server side session storage to work. Without the workaround, an exception is performed by the runtime, when the service tries to add your data to the session object.

If you want to use both, add the BrowserSessionStorage and ServerSessionStorage as keyed services:

...
builder.Services.AddKeyedScoped<ISessionStorage, ServerSessionStorage>("server");

builder.Services.AddKeyedScoped<ISessionStorage, BrowserSessionStorage>("browser");
...

For further information, see the demo project.

Key of data stored in the session storage

When you store data in the session storage, you must provide a 'key'. As the session store is global for the session in your application, you must consider if the same key is to be used across your components. That is, if you have ComponentA and ComponentB, then setting/getting data having key 'CustomerNbr' will return the same data.

If you want to use the same key in several components, you must extend the key name e.g. by adding the component name like this:

...
var key = $"{this.GetType().Name}-ComponentWidth";
...

Found a bug?

Please create an issue in the repo.

Known issues (Work in progress)

The workaround explained above, must be applied for server side session storage to work.

FAQ

How do I store a 'long'?

There is no 'SetLongAsync()' method, so what you have to do is, to call the SetAsync() method like this:

...
long myLong = 1234567L;
await sessionStorage.SetAsync("mylong", mylong);
...

To read it back, call GetAsync() method:

...
long? myLong = await sessionStorage.GetAsync<DemoData>("mylong");
...

About

Provides client and/or server side session storage for a Blazor application.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published