Dagovax
Dagovax

Reputation: 165

How to store an unique Blazor sessionID for each client?

We are using a shared Razor Class Library for our Blazor applications containing all components, that both our Blazor Server and Blazor WebAssembly startup projects are using.

However, when we open another tab or browser window, going to the same URL, we noticed that the session persists.

We tried creating an unique guid in JavaScript, and invoking it to the app using IJSRuntime. That unique guid is then used inside all components to show the correct data loaded from our API. It doesn't always work however, and it is not good perfomance wise either.

Because we are using a shared Razor Class Library, we are not able to use the ProtectedSessionStorage. How can we get unique sessions without using JavaScript interop calls?

Upvotes: 2

Views: 3048

Answers (1)

nogood
nogood

Reputation: 1330

To give each Window/BrowserTab-Session a unique-Id just add a scoped service in Program.cs. If this is what your want.

enter image description here

Each instance of the App gets a unique Id that can be passed on to your library-components, in order to identify a tab/window instance as long as this session lastes.

Code for Blazor Webassably

Add in Program.cs

     builder.Services.AddScoped<MyIdService>();

Add the MyIdService.cs class

    public class MyIdService
    {
        public Guid MyGuid { get; set; } = Guid.NewGuid();
    }

Add/inject this to every page you need this behavior. Or to make it more simple just add it to the shared/mainlayout.razor file.


    @inherits LayoutComponentBase
    @inject MyIdService MyIdService
    
    <div class="page">
        <div class="sidebar">
            <NavMenu />
        </div>
    
        <main>
            <div class="top-row px-4">
                <h4>@MyIdService.MyGuid</h4>
            </div>
    
            <article class="content px-4">
                @Body
            </article>
        </main>
    </div>

The Id is only good as long as a user session lasts. If you want to store state of every user for later use. You would need a userlogin and some sort of datapersisting.

Upvotes: 6

Related Questions