Blazor Web App 项目模板( .NET 9.0 )Session 使用备忘

一、使用 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();

............

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值