HttpContext.Current.User.Identity.Name 为空

Posted

技术标签:

【中文标题】HttpContext.Current.User.Identity.Name 为空【英文标题】:HttpContext.Current.User.Identity.Name is null 【发布时间】:2014-08-01 12:32:04 【问题描述】:

我正在尝试使用 HttpContext.Current.User.Identity.Name 从内部网络获取用户的 Windows 登录详细信息,但是它是空的。

我已经尝试在 Web.Config 中更改身份验证模式,但并不高兴:

  <system.web>
    <authentication mode="Windows" />
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>

我还听说在项目属性中您应该启用 Windows 身份验证并禁用匿名身份验证,如下所示:

然后我得到一个重定向循环,在 Chrome 中显示“此网页有重定向循环”消息。

我还检查了我的机器上是否安装了 Windows 身份验证:

请问有什么解决办法吗?

非常感谢

【问题讨论】:

用户登录时是否使用此方法:FormsAuthentication.SetAuthCookie("user name",true); 谢谢,我刚刚尝试将它添加到我的家庭控制器中,但不幸的是我仍然遇到同样的错误 请尝试使用默认设置(因为您已修改它们) 这对我有用:@if (Request.IsAuthenticated) @Html.Encode(User.Identity.Name) @html.ActionLink("Sign Out", “注销”、“主页”) 如果它在您的本地工作站上,您可能想尝试设置 【参考方案1】:

当我有:

<authentication mode="Windows"/>
<identity impersonate="true/>

在 web.config 我得到当前用户:

string currUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

【讨论】:

非常感谢您的回复,但是我收到以下错误:已检测到不适用于集成托管管道模式的 ASP.NET 设置。最可能的原因:system.web/identity@impersonate 设置为 true。 除此之外,我摆脱了错误:***.com/questions/4209999/… 但不幸的是,System.Security.Principal.WindowsIdentity.GetCurrent().Name 的值仍然为 null :(【参考方案2】:

将我的项目 Web 服务器设置更改为 Local IIS 而不是 IIS Express 为我解决了这个问题,但如果有人对此有更多信息,我不确定为什么会出现这种情况。

右键单击项目 点击属性 转到网络标签 在“服务器”部分,从下拉列表中选择 Local IIS

【讨论】:

以上是关于HttpContext.Current.User.Identity.Name 为空的主要内容,如果未能解决你的问题,请参考以下文章

HttpContext.Current.User.Identity.Name 为空

HttpContext.Current.User.Identity.Name 每次都是空的

将 HttpContext.Current.User 与异步等待一起使用的正确方法

HttpContext.Current.User.Identity.Name为Empty

ASP.NET C#中怎么让 httpcontext.current.user.identity.name 获取为自定义的值

WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;如何使这个演员工作;目前它失败了