3

Я хочу сохранить userId в файле cookie в ASP.NET Core MVC. Где я могу получить к нему доступ?Извлечь Userid из формулы в cookie в Core MVC

Логин:

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) 
); 

Get UserId:

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

Update - Скриншот Добавлено формулы изобретения, которые являются нуль -------

userId также null.

enter image description here

ответ

7

Вы должны быть в состоянии получить его через 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(); 
} 
+0

будет проверять позже. Но я уверен, что я попробовал «User.Claims», которые являются «нулевыми». Я не знаю, почему хотя :) – radbyx

+0

Это также null. Я уверен, что ваша строка верна, но мне нужно что-то еще, я думаю. Как-то в StartUp.cs я еще не добавил. ASP.NET Core MVC для меня новичок, поэтому я, возможно, не добавил никаких дополнительных зависимостей, чтобы рекламация работала. – radbyx

+0

См. Добавленный скриншот :) – radbyx