Asp.net身份:User.Identity.GetUserId()始终为null,User.Identity.IsAuthenticated总是为假

时间:2014-08-22 03:52:23

标签: asp.net-mvc asp.net-mvc-5.2

请参阅下面的代码:

var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
    case SignInStatus.Success:
        string UserId = User.Identity.GetUserId(); 
        return RedirectToAction("ClientDetails","Home");
    case SignInStatus.LockedOut:
        return View("Lockout");
    case SignInStatus.RequiresVerification:
        return RedirectToAction("SendCode", "Account", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
    case SignInStatus.Failure:
    default:
        ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
}

UserId始终为nullUser.Identity.IsAuthenticated始终为false。但我可以查看需要身份验证的视图ClientDetails

3 个答案:

答案 0 :(得分:17)

我假设您的示例是来自AccountController.Login()方法的代码。我遇到了与您相同的问题,但发现在下一个请求之前不会填充User对象。试试这种方法:

case SignInStatus.Success:
    return RedirectToAction("DoWork", "Account");


public async Task<ActionResult> DoWork()
{
    //this works
    string UserId = User.Identity.GetUserId();
    //return to View or Redirect again
}

答案 1 :(得分:13)

对于&#34; UserId始终为null&#34;问题的一部分,您可以通过model.UserName:

查找用户
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
    case SignInStatus.Success:
        ApplicationUser user = UserManager.FindByName(model.UserName);
        string UserId = user.Id;
        // UserId is now populated
        return RedirectToAction("ClientDetails","Home");

等。不确定您是否希望User.Identity.IsAuthenticated为true或者这是否是观察 - 这不会改变该部分。

答案 2 :(得分:0)

使用[授权]标记方法后与我合作 属性并在授权标头中发送访问令牌,似乎需要访问令牌来识别用户