MVC5 User.Identity.GetUserName()在Controller中为Null

时间:2014-04-27 22:50:02

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

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

我正在查看该页面,并且UserName显示在标题中,如果我点击指向我尝试使用它的控制器的链接,我会得到一个空引用异常。< / p>

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

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

所以我只是好奇。

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

User对象向Controller公开,因此您无需通过System.Web.HttpContext.Current访问它。

var myUserName = User.Identity.GetUserName();

答案 2 :(得分:0)

这很有效。

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

答案 3 :(得分:0)

还要确保您没有

<authentication mode="None" />

像我刚在您的Web.config中一样。

相关问题