【问题标题】:MVC5 User.Identity.GetUserName() is Null in ControllerMVC5 User.Identity.GetUserName() 在控制器中为 Null
【发布时间】:2014-04-27 22:50:01
【问题描述】:

这里发生了什么? User.Identity.GetUserName() 在视图中可以正常工作,例如在登录部分视图中。但是如果我在控制器中使用它,它会抛出一个空引用异常。

我正在查看页面,并且用户名显示在标题中,然后如果我单击指向我尝试使用它的控制器的链接,我会得到一个空引用异常。

我应该补充一下,如果我这样做,它可以正常工作:

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

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

【问题讨论】:

  • 我也有同样的问题:(

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    User 对象暴露给 Controller,因此您无需通过 System.Web.HttpContext.Current 访问它。

    var myUserName = User.Identity.GetUserName();
    

    【讨论】:

    • 这正是我所做的 Brendan,它抛出了一个空引用异常。
    • 控制器是否标记为 AllowAnonymous?如果您有来自同一个控制器的视图工作正常,那么可能还有其他事情发生。
    【解决方案3】:

    这行得通。

    public static class GetUserName
    {
        public static string Name(IPrincipal user)
        {
            return user==null? HttpContext.Current.User.Identity.Name:user.Identity.Name;
        }
    }
    

    【讨论】:

      【解决方案4】:

      还要确保你没有

      <authentication mode="None" />
      

      像我刚才那样在你的 Web.config 中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-28
        • 1970-01-01
        • 2014-11-28
        相关资源
        最近更新 更多