ASP.NET标识不会更新同一请求的标识信息

Tod*_*odd 6 c# asp.net claims-based-identity owin asp.net-identity

我正在使用AngularJS和ASP.NET Identity 2处理单页应用程序.我将用户登录并设置了cookie; 但是,当我在同一请求中检查用户的身份时,它会将其显示为空白,并且IsAuthenticated为false.但是,这些都会在后续请求中填充.我希望无论用户是否在同一请求中登录,都会向UI发回.这可能吗?

代码按要求(AngularJS使AJAX发布到WebAPI控制器登录方法)

[HttpPost]
[AllowAnonymous]
[Route("Login")]
public async Task<IHttpActionResult> Login(LoginModel loginModel)
{
    var result = await _securityService.Login(loginModel.UserName, loginModel.Password);
    if (!result)
    {
        ModelState.AddModelError("errorMessage", "Invalid username or password.");
        return BadRequest(ModelState);
    }
    return Ok();
}

public async Task<bool> Login(string userName, string password, bool persistCookie = false)
{
    var user = await _userManager.FindAsync(userName, password);
    if (user != null)
        await SignInAsync(user, persistCookie);
    else
        return false;

    return true;
}

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    _authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    _authenticationManager.SignIn(new AuthenticationProperties() {IsPersistent = isPersistent}, await CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie));
}

public Task<ClaimsIdentity> CreateIdentity(ApplicationUser user, string authenticationType)
{
    return _userManager.CreateIdentityAsync(user, authenticationType);
}
Run Code Online (Sandbox Code Playgroud)

Hao*_*ung 5

在下一个请求之前,您不会获得已签名的身份,因为对SignIn的调用是导致在响应上设置cookie的原因.该cookie将在后续请求中变为身份,但是为时已晚,无法更改当前请求的身份.