Home > Blockchain >  What replaces Session variables in Blazor Web Assembly?
What replaces Session variables in Blazor Web Assembly?

Time:01-18

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.

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

The best way to handle this is to add a CascadingParameter parameter property of Task type in your components, and access the AuthenticationState object which exposes a ClaimsPrincipal object. From there you can access the user's claims, etc.

Note: The App component in your Blazor client project contains a CascadingAuthenticationState component from which the AuthenticationState is cascaded down. If your app is missing the CascadingAuthenticationState, it means that your authentication mechanism is not the one that comes with the default template (Identity provider), but a custom one, meaning that you've created it yourself, as for instance, a Jwt Token authentication. In which case, you'll have to implement the AuthenticationStateProvider object, adding manually the claims provided by the Jwt Token to the AuthenticationState object. This is a little bit complicated and requires some knowledge how to do that.

Note that you can easily access the Session State and local state from Blazor, and store in them data you can access from every nook of your app... better from a single location, using a dedicated class service.

  •  Tags:  
  • Related