What replaces Session variables in Blazor Web Assembly?

So in a .Net web forms project, I would simply use session variables to be able to set and get them across different pages. What is the proper way to do that in Blazor Web Assembly (with core hosting) ? i.e a user logs in, things like their ID, email, first name, etc are stored and then needed to be accessed in other pages.


Solution 1:

in a .Net web forms project, I would simply use session variables

Your Wasm app is a regular C# app so you can use most normal storage mechanisms. I would stay away from static but you can use your own SessionStateService. Just a bunch of properties. Inject it as a singleton or use it as a Cascading value.

But ye old Session data was stored server-side. That means there is a subtle difference with Blazor wasm solutions as soon as the user opens a second tab with the same app. Every tab runs its own instance of the app so your data will be local to that tab. There is no sharing.

When you do want to share between tabs, use JavaScripts localstorage (persisted) or create an endpoint on your API server (persistance is up to you).

things like their ID, email, first name

Those should preferably be stored as claims in a JWT. Especially when you want to base some (serverside) authorization or logic on those values.

Solution 2:

You use a Scoped DI service to maintain state, and inject it into any components that need to use or add/update the information.

See Ms Docs - https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/dependency-injection?view=aspnetcore-6.0