我对ASP比较陌生.Net MVC并try 使用内置的用户登录功能.我可以在注册视图中注册用户.如果我try 使用创建的用户登录,这同样有效.我被重定向到母版页.

但我无法获取当前用户的用户ID.我在HomeController和AccountController中try 了我的代码,但都不起作用.第一行中的语句始终返回null.

var userID = User.Identity.GetUserId();

if (!string.IsNullOrEmpty(userID))
{
    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
    var currentUser = manager.FindById(User.Identity.GetUserId());
}

在获取用户ID之前,我需要做其他事情吗?

推荐答案

答案就在您的代码中.这会返回什么?

var userID = User.Identity.GetUserId();

如果你正在使用ASP.NET身份,然后after登录(并重定向到另一个页面),IPrincipal.IIdentity应该是ClaimsIdentity.你可以试试这个:

var claimsIdentity = User.Identity as ClaimsIdentity;
if (claimsIdentity != null)
{
    // the principal identity is a claims identity.
    // now we need to find the NameIdentifier claim
    var userIdClaim = claimsIdentity.Claims
        .FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

    if (userIdClaim != null)
    {
        var userIdValue = userIdClaim.Value;
    }
}

上面的挡路代码并不完全是IIdentity.GetUserIdExtension方法所做的,但从本质上讲,它是IIdentity.GetUserIdExtension方法所做的.

如果这些都不起作用,那么用户可能还没有真正登录到您的站点.登录后,您必须重定向到另一个页面,然后服务器才会将身份验证cookie写入浏览器.此cookie必须在User.Identity具有所有这些索赔信息(包括NameIdentifier)on subsequent requests之前写入.

Asp.net相关问答推荐

如何根据另一个下拉列表中的 Select 从下拉列表中删除一个值?

我可以在一个 Web 项目中有多个 web.config 文件吗?

如何将 JQuery 与母版页一起使用?

使 ASP.NET WCF 将字典转换为 JSON,省略键和值标签

返回 HttpResponseMessage 时的 WebAPI Gzip

获取没有主机的 url 部分

如何从以特定名称开头的 appsettings 键中获取所有值并将其传递给任何数组?

有没有办法在外部 javascript 文件中使用<%= someObject.ClientID %>?

如何在页面的基类中执行 Page_Load()?

如何在txt文件中保存异常?

使用 Lucene.NET 索引 .PDF、.XLS、.DOC、.PPT

Webapi、Webhost和Owin的关系

配置转换和TransformXml 任务失败错误消息

*.csproj 中的 usevshostingprocess 是什么?

ServiceStack 示例应该以什么顺序被理解?

在 ASP.NET 中使用 MasterPages 时使用 JQuery 的正确方法?

验证请求事件

在后面的代码中删除 css 类

IIS url 重写角色,除了一些 url

您将如何将 ASP.Net MVC 嵌入到现有的网站项目中?