User.Identity.GetUserId()始终在控制器操作中返回null

时间:2017-04-07 15:04:57

标签: asp.net asp.net-mvc asp.net-mvc-5 iidentity

我需要在控制器中使用当前登录的用户ID。它总是返回null。我已经登录了。这是我的代码。

if (string.IsNullOrEmpty(userId)) userId = User.Identity.GetUserId();

我尝试添加引用

 using Microsoft.AspNet.Identity;

我也尝试添加声明

public const string UserId = "http://schemas.xmlsoap.org/ws/2014/03/mystuff/claims/UserId";
userIdentity.AddClaim(new Claim(CustomClaimTypes.UserId, Id));

当我尝试检索声明时,它也会返回null。

(identity as ClaimsIdentity).FirstOrNull(CustomClaimTypes.UserId);

任何帮助都将不胜感激。

评论中要求的其他信息:

这是aspnetuser提供的正常登录。

        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                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);
        }

Request.IsAuthenticated返回true。

此处添加了声明。

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        userIdentity.AddClaim(new Claim(CustomClaimTypes.UserId, Id));

        return userIdentity;
    }

Cookies

1 个答案:

答案 0 :(得分:0)

这是答案,我设法让它发挥作用。

我刚将User.Identity.GetUserId();移动到辅助类方法。

我只想重申一下,请求不是登录请求。登录后它是一个单独的请求。

谢谢你们的时间。

相关问题