rad*_*byx 5 cookies asp.net-mvc claims-based-identity asp.net-identity asp.net-core-mvc
我想在ASP.NET Core MVC中将userId存储在cookie中.我在哪里可以访问它?
登录:
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
});
Run Code Online (Sandbox Code Playgroud)
登出:
User.Identity.GetUserId(); // <-- 'GetUserId()' doesn't exists!?
ClaimsPrincipal user = User;
var userName = user.Identity.Name; // <-- Is null.
HttpContext.Authentication.SignOutAsync("Cookie");
Run Code Online (Sandbox Code Playgroud)
这可能在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)
);
Run Code Online (Sandbox Code Playgroud)
获取UserId:
public ActionResult TestUserId()
{
IPrincipal iPrincipalUser = User;
var userId = User.Identity.GetUserId(); // <-- Working
}
Run Code Online (Sandbox Code Playgroud)
更新 - 添加了声明为null的屏幕截图-------
userId也是null.
klo*_*eek 11
你应该可以通过HttpContext获取它:
var userId = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
Run Code Online (Sandbox Code Playgroud)
在示例上下文中是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();
}
Run Code Online (Sandbox Code Playgroud)
使用ClaimsPrincipal类的FindFirst方法:
var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
| 归档时间: |
|
| 查看次数: |
8572 次 |
| 最近记录: |