向用户添加声明时,声明信息不会作为 Cookie 记录在页面上,并且对于所有其他请求,该信息都会丢失。为什么会出现这种情况?
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
try
{
var authReq = new AuthenticationViewModel() { password = model.Password, username = model.UserName };
var userInfo = await _dataService.AuthenticateAsync(authReq);
var claims = new List<Claim>();
claims.Add(new Claim("username", userInfo.user.userName));
claims.Add(new Claim("AddtionalData", userInfo.AddtionalData));
var user = ClaimsPrincipal.Current;
var identity = user.Identities.Where(x => x.AuthenticationType == "Custom").FirstOrDefault();
if (identity == null)
identity = new ClaimsIdentity(claims.ToArray(), "Custom");
user.AddIdentity(identity);
return RedirectToAction("Users", "Index");
}
catch (Exception)
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
最佳答案
我发现了这个问题,我需要添加以下代码:
context.Response.SignIn(new ClaimsIdentity(new[] { new Claim("name", "bob") }, CookieAuthenticationDefaults.AuthenticationType));
此外,我将 AuthenticationType 更改为 CookieAuthenticationDefaults.AuthenticationType。
请参阅 Sample 的链接
关于asp.net-core - 声明身份验证 ASP.NET vNext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26978158/