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:
- Configure session state in the program.cs file:
and set the UseSession middleware.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; });
app.UseSession();
- Then in the Razor page, you can refer to the following code to use session:
[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 Corepublic 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); } }
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