Asp.net-Mvc

從 Core MVC 中的 cookie 中的聲明中檢索使用者 ID

  • March 22, 2018

我想在 ASP.NET Core MVC 中的 cookie 中儲存一個 userId。我在哪裡可以訪問它?

登錄:

var claims = new List<Claim> {
   new Claim(ClaimTypes.NameIdentifier, "testUserId")
};

var userIdentity = new ClaimsIdentity(claims, "webuser");
var userPrincipal = new ClaimsPrincipal(userIdentity);
HttpContext.Authentication.SignInAsync("Cookie", userPrincipal,
   new AuthenticationProperties
   {
       AllowRefresh = false
   });

登出:

User.Identity.GetUserId(); // <-- 'GetUserId()' doesn't exists!?

ClaimsPrincipal user = User;
var userName = user.Identity.Name; // <-- Is null.

HttpContext.Authentication.SignOutAsync("Cookie");

在 MVC 5 中是可能的 ——————–>

登錄:

// Create User Cookie
var claims = new List<Claim>{
       new Claim(ClaimTypes.NameIdentifier, webUser.Sid)
   };

var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(
   new AuthenticationProperties
   {
       AllowRefresh = true // TODO 
   },
   new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie)
);

獲取使用者 ID:

public ActionResult TestUserId()
{
   IPrincipal iPrincipalUser = User;
   var userId = User.Identity.GetUserId(); // <-- Working
}

更新 - 添加了無效聲明的螢幕截圖 ——–

userId也是null

在此處輸入圖像描述

您應該能夠通過 HttpContext 獲取它:

var userId = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;

在範例上下文中是 HttpContext。

Startup.cs(只是模板網站中的基礎知識):

public void ConfigureServices(IServiceCollection services)
{
   services.AddIdentity<ApplicationUser, IdentityRole>()
       .AddEntityFrameworkStores<ApplicationDbContext>()
       .AddDefaultTokenProviders();
   services.AddMvc();
}

public void Configure(IApplicationBuilder app)
{
   app.UseIdentity();
   app.UseMvc();
}

引用自:https://stackoverflow.com/questions/41242934