asp.net-mvc - MVC5 User.Identity.GetUserName() 在 Controller 中为 Null

标签 asp.net-mvc asp.net-mvc-5 identity

这是怎么回事? User.Identity.GetUserName() 在 View 中工作正常,例如在登录部分 View 中。但如果我在 Controller 中使用它,它会抛出空引用异常。

我正在查看页面,用户名显示在标题中,然后,如果我单击指向我尝试使用它的 Controller 的链接,则会收到空引用异常。

我应该补充一点,如果我这样做,效果很好:

        var httpContext = System.Web.HttpContext.Current;
        _userName = httpContext != null ? httpContext.User.Identity.Name : "Testing";

所以大多数时候我只是好奇。

最佳答案

您将调用User.Identity.GetUserName();的代码放在哪里??如果它是在构造函数上,那么您将得到空引用异常 - 因为对象 User 尚未在构造函数中初始化。

关于asp.net-mvc - MVC5 User.Identity.GetUserName() 在 Controller 中为 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23330022/

相关文章:

c# - 分页列表错误 : The method 'OrderBy' must be called before the method 'Skip'

asp.net-mvc - T4MVC 不支持 DisplayTemplates 和 EditorTemplates

c# - 请求被中止无法在共享主机服务器 C# 上创建 ssl/tls 安全通道

c# - UserManager 的异步方法给出 "Incorrect number of arguments for call to method Boolean Equals"

c# - 确定文件身份的算法(优化)

c# - 从 Fluent NHibernate 中的种子表生成身份

c# - 即使在使用 Identity ASP.NET MVC 框架关闭浏览器后,如何让用户保持登录状态?

asp.net-mvc - “A potentially dangerous Request.Form value was detected from the client”

asp.net-mvc - 将 javascript 文件存储在与 ASP.NET Core 1.1 中的 View 相同的文件夹中?

c# - 我希望我的页面以 2 条路线打开。我应该怎么办