一、使用 ProtectedSessionStorage 写入、读取 sessionStorage 中的内容
@page "/SessionTest"
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
@inject ProtectedSessionStorage SessionStorage
<h3>SessionTest</h3>
<Button OnClick="SessionTestCliick" Text="设置" />
<div>@SessionStorage.ToString()</div>
<div>xx1:@xx1</div>
<div>xx2:@xx2</div>
@code {
int xx1;
int xx2;
private async void SessionTestCliick()
{
var x1 = await SessionStorage.GetAsync<int>("key1");
var x2 = await SessionStorage.GetAsync<int>("id2", "key2");
xx1 = x1.Value;
xx2 = x2.Value;
xx1++;
xx2++;
await SessionStorage.SetAsync("key1", xx1);
await SessionStorage.SetAsync("id2", "key2", xx2);
StateHasChanged();
}
}
注1: sessionStorage 中保存的内容在关闭 浏览器标签 或者 浏览器 时清除。
二、传统 Session 使用可以通过 HttpContext.Session 或者 SignInManager.Context.Session 实现
s1 = SignInManager.Context.Session.GetInt32("key-s1") ?? 0;
SignInManager.Context.Session.SetInt32("key-s1", s1);
注2:使用此方法,需要在 Program.cs 中 builder.Services.AddSession、app.UseSession()。
............
/*使用 Session 功能:配置会话状态*/
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
//默认为 20 分钟
//options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
var app = builder.Build();
............
app.UseAntiforgery();
/*使用 Session 功能:在 UseRouting 之后和 MapRazorPages 与 MapDefaultControllerRoute 之前调用 UseSession。
调用 UseSession 以前无法访问 HttpContext.Session。*/
app.UseSession();
app.MapStaticAssets();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
............