HttpContext.User.Identity.Name返回空白

时间:2012-12-18 18:23:53

标签: c# asp.net-mvc

我想弄清楚为什么HttpContext.User.Identity.Name会返回空白。

代码

    public ActionResult Test()
    {
        string username = HttpContext.User.Identity.Name;
        return Content(username);         
    }

我是否在错误的环境中使用它?我想获取用户的用户名。

的Web.Config

<authentication mode="Windows" />

IIS

我启用了匿名,没有其他任何内容被检查。我正在运行IIS 6.0。

我是否需要添加任何类型的信息以帮助解决这个问题?我很困惑。我查了一下:http://stackoverflow.com/questions/1056487/httpcontext-current-user-identity-name-is-always-string-empty但我是否需要设置一个Cookie才能使其正常工作?

4 个答案:

答案 0 :(得分:3)

IsAuthenticated返回false,因此Identity.Name返回空字符串,因为您没有要求对该操作进行身份验证。您必须启用Windows身份验证并要求对操作进行身份验证。尝试通过使用[Authorize]属性进行装饰来要求用户获得操作的授权 - 这将启动身份验证协商。

[Authorize]
public ActionResult Test()
{
    if(Request.IsAuthenticated)
    {
        string username = HttpContext.User.Identity.Name;
        return Content(username);         
    }
    else 
    {
        return Content("User is not authenticated");
    }
}

答案 1 :(得分:2)

  

我启用了匿名,没有其他任何内容被检查。我正在运行IIS   6.0。

这意味着系统不会提示您登录,因此User.Identity.IsAuthenticated将为false,User.Identity.Name将为空。

取消选中匿名身份验证并检查Windows身份验证。

答案 2 :(得分:2)

如果其他人遇到此问题,请验证&#34;加载用户个人资料&#34;选项设置为 true 。转到IIS应用程序池。从列表中选择您的应用程序池。单击“高级设置”并向下滚动到“处理模型”部分。

这解决了我的问题。

答案 3 :(得分:0)

如果您使用的是FormsAuthentication.SetAuthCookie 那么你需要添加

<authentication mode="Forms" />

<System.Web>
在Web.config文件中

。 来自here

的解决方案
相关问题