在 .net core 5.0 中跨所有控制器访问会话变量

Access session variables across all controllers in .net core 5.0

我已经对此进行了研究一分钟,但似乎没有任何效果。我希望能够在不同的时间点设置多个会话变量并跨所有控制器访问它们。

我试过以下方法:

我创建了一个基本控制器并设置了一个 public 我想要访问的变量字符串。

 public class BaseController : Controller
    {
       public string UserToken
        {
            get
            {
                string token = HttpContext.Session.GetString("SessionUserToken");
                return token == null ? null : token.ToString();
            }
            set
            {
                HttpContext.Session.SetString("SessionUserToken", value);
            }
        }
    }

然后我从基本控制器继承到我的家庭控制器

 public class HomeController : BaseController
 { 
    public async Task<IActionResult> Index()
    {
            string userToken = HttpContext.Session.GetString("SessionUserToken"); ;
            if (userToken == null)
              //do something
            else 
             //do something else
    }
       
 }

还有另一个控制器

 public class ProfileController: BaseController
 { 
    public async Task<IActionResult> Login(LoginModel login)
    { 
       Login account = await _Repository.Login(login);
          if(account.succeeded)
           {
               UserToken = account.data;
           }else{
              redirectToAction("Index", "Home");
           }
           
    }
       
 }

有谁知道我怎样才能做到这一点?

看起来你的 re-creating 中的身份验证系统 ASP.NET

我非常建议您考虑使用已经内置的 Cookie 身份验证系统。这不需要您使用 ASP.NET 身份。

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-6.0

在您的启动文件中,您必须设置

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
        options.SlidingExpiration = true;
        options.AccessDeniedPath = "/Forbidden/";
    });

然后在您的 ProfileController 中,您可以运行下面的代码来设置身份验证 cookie。

var claimsIdentity = new ClaimsIdentity(new List<Claim>
{
    new Claim("SessionUserToken", account.data)
}, CookieAuthenticationDefaults.AuthenticationScheme);

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme, 
    new ClaimsPrincipal(claimsIdentity), 
    new AuthenticationProperties());

然后您可以使用 [Authorize] 等经典属性验证访问权限,或者您可以检查 User.Identity.IsAuthenicated,当您需要 SessionUserToken 时,您可以访问 User.FindFirstValue("SessionUserToken")