Sessions in Blazor ASP.Net app

Filippo 41 Reputation points
2022-12-01T15:44:34.337+00:00

Hello, i'm new to Blazor pages.

I cannot find how to use sessions in blazor project.
FOR EXAMPLE, in my file myfile.cshtml.cs i catch the post of a form

Ho do i write the session variables? and then how do i read ?

public void OnPostSubmit(string formUsername, string formPassword, User user)  
{      
     this._user = user;  
     // here i want to load the username and password previously saved in session variables.  
     
}  
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,612 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,546 Reputation points Microsoft Vendor
    2022-12-02T06:23:38.957+00:00

    Hi @Filippo ,

    I cannot find how to use sessions in blazor project.

    Whether your application is a Blazor server application or a Blazor WebAssembly application?

    If it is a Blazor server application, you can try to use the browser's localStorage and sessionStorage collections, or you can try to use ASP.NET Core Protected Browser Storage, code like this:

    @using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage  
    @inject ProtectedSessionStorage ProtectedSessionStore  
    
    private async Task IncrementCount()  
    {  
        currentCount++;  
        await ProtectedSessionStore.SetAsync("count", currentCount);  
    }  
    

    Then, to get the value from the Protected Session, use the GetAsync method:

    protected override async Task OnInitializedAsync()  
    {  
        var result = await ProtectedSessionStore.GetAsync<int>("count");  
        currentCount = result.Success ? result.Value : 0;  
    }  
    

    If the application is a Blazor WebAssembly application, you can try to use browser's localStorage and sessionStorage collections.

    Besides, you can also store the data into database or use the In-memory state container service. More detail information, refer to the following articles:

    ASP.NET Core Blazor Server state management

    ASP.NET Core Blazor WebAssembly state management

    Update:

    To use session in Razor page application, you could refer the following steps and code:

    1. Configure session state in the program.cs file:
      builder.Services.AddDistributedMemoryCache();  
      
      builder.Services.AddSession(options =>  
      {  
          options.IdleTimeout = TimeSpan.FromSeconds(10);  //you can change the session expired time.  
          options.Cookie.HttpOnly = true;  
          options.Cookie.IsEssential = true;  
      });  
      
      and set the UseSession middleware.
      app.UseSession();  
      
    2. Then in the Razor page, you can refer to the following code to use session:
      public class IndexModel : PageModel  
      {  
          public const string SessionKeyName = "_Name";  
          public const string SessionKeyAge = "_Age";  
      
          private readonly ILogger<IndexModel> _logger;  
      
          public IndexModel(ILogger<IndexModel> logger)  
          {  
              _logger = logger;  
          }  
      
          public void OnGet()  
          {  
              if (string.IsNullOrEmpty(HttpContext.Session.GetString(SessionKeyName)))  
              {  
                  HttpContext.Session.SetString(SessionKeyName, "The Doctor");   //set session  
                  HttpContext.Session.SetInt32(SessionKeyAge, 73);  
              }  
              var name = HttpContext.Session.GetString(SessionKeyName);   //get session value.   
              var age = HttpContext.Session.GetInt32(SessionKeyAge).ToString();  
      
              _logger.LogInformation("Session Name: {Name}", name);  
              _logger.LogInformation("Session Age: {Age}", age);  
          }  
      }  
      
      [Note]If you want to use session to store object, you need to add the SessionExtensions. More detailed information, see Session and state management in ASP.NET Core

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 67,921 Reputation points
    2022-12-01T16:07:06.647+00:00

    As blazor server is only one request, session is not needed. Just store the user in a state variable, access the HttpContext, or best solution inject an ApiAuthenticationStateProvider

    https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-7.0

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.