NET 7 中使用Session

NET 7 中使用Session
2024年2月11日 net7下测试通过
Program.cs关键代码:
      builder.Services.AddDistributedMemoryCache();

        builder.Services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });

        builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  //....
  
    app.UseSession();

母版页_Layout.cshtml中使用:

@using Microsoft.AspNetCore.Http
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor;

<div class="rtm r3">
 @if(_httpContextAccessor.HttpContext.Session.GetInt32("loginid") == null){
    <a href="javascript:;" class="rg1" onclick="login(2)">注册</a>
        <a href="javascript:;" class="rg2" onclick="login(1)">登录</a>
}
else
{
<span>欢迎您,
    @_httpContextAccessor.HttpContext.Session.GetString("loginname")
    ,</span>
<a href="/home/loginout" class="rg2">退出登录</a>
}
</div>

 

posted @ 2024-02-11 20:24  牛腩  阅读(7)  评论(0编辑  收藏  举报