c# - ASP.NET身份用户登录后为空

标签 c# asp.net-mvc-5 asp.net-identity-2

编辑 1

更新了代码以更好地处理这个问题后,我现在遇到了以下问题:

The provided anti-forgery token was meant for a different claims-based user than the current user.

这是更新后的代码:

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
if (result == SignInStatus.Success)
{
    var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
    var manager = new UserManager<ApplicationUser>(store);
    var user = manager.FindById(User.Identity.GetUserId());
    GenerateUserCookie(model, user, returnUrl);
}
switch (result)
{
    case SignInStatus.LockedOut:
        return View("Lockout");
    case SignInStatus.RequiresVerification:
        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
    case SignInStatus.Failure:
        ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
    default:
        return View(model);
}

private ActionResult GenerateUserCookie(LoginViewModel model, ApplicationUser user, string returnUrl)
{
    if (user == null)
    {
        ModelState.AddModelError("", "Someething went wrong; please try logging in again.");
        return View(model);
    }

    var cookie = new HttpCookie("stman");
    if (user.AgentId >= 1) cookie.Values.Add("aid", user.AgentId.ToString());

    cookie.Values.Add("wumpus", user.Id.ToString());
    Response.Cookies.Add(cookie);
    return RedirectToLocal(returnUrl);
}

原始问题

如标题所示,我登录后,以下代码返回的user值仍然为null。

要真正获得用户,我必须再次打开登录屏幕(而不是刷新)并再次登录...

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // This doesn't count login failures towards account lockout
    // To enable password failures to trigger account lockout, change to shouldLockout: true
    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
    switch (result)
    {
        case SignInStatus.Success:
            var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
            var manager = new UserManager<ApplicationUser>(store);
            var user = manager.FindById(User.Identity.GetUserId());
            GenerateUserCookie(user);
            return RedirectToLocal(returnUrl);
        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}

private void GenerateUserCookie(ApplicationUser user)
{
    var cookie = new HttpCookie("stman");

    // Throws exception most times since the user is null.
    if (user.AgentId >= 1)
    {
        cookie.Values.Add("aid", user.AgentId.ToString());
    }
    cookie.Values.Add("wumpus", user.Id.ToString());
    Response.Cookies.Add(cookie);
}

最佳答案

问题是 User.Identity 在您重定向之前不可用。解决此问题的一个简单方法是使用用户名而不是 id 来获取正确的 ApplicationUser

var manager = new UserManager<ApplicationUser>(store);
var user = manager.FindByName(model.UserName);
GenerateUserCookie(user);

关于c# - ASP.NET身份用户登录后为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52540896/

相关文章:

c# - 托管C++,形成C#和C++之间的桥梁

c# - 在调试函数以获取数组中字符的 XY 方面需要帮助

asp.net-web-api - 网络 API 2 : Authorising against custom claims

c# - 如果对象的属性是 "bigger"而不是 c# 中的另一个对象,则禁止编译

c# - 使用 OpenXML SDK 2.5 将图片添加到 QuickPart Autotext

c# - nlog 不创建文件

asp.net - 如何将ASP.NET MVC5身份验证添加到现有数据库

c# - 如何将 Dictionary 绑定(bind)到 ASP.NET MVC 5 Razor 模板引擎中的部分 View

asp.net-mvc - 如何使用身份2中的电子邮件登录?

c# - ASP.Net Identity 2 - 来自 OAuthAuthorizationServerProvider 的自定义响应