1

我需要在控制器中使用当前登录的用户 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返回真。

此处添加了声明。

    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;
    }

饼干

4

1 回答 1

0

这是答案,我设法让它工作。

我只是将其User.Identity.GetUserId();移至辅助类方法。

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

谢谢你们的时间。

于 2017-04-08T13:37:55.977 回答