HttpContext.Current.User.Identity.Name返回空白

And*_*dy5 12 asp.net windows-identity

我正在使用HttpContext.Current.User.Identity.Name来获取Web应用程序正在使用时的用户名.在开发过程中,我使用了我的本地iis,启用了集成的Windows身份验证,启用了匿名访问和禁用,我能够获得用户名.

现在,当我发布Web应用程序时,它又回来了.已发布服务器上的设置是相同的,我尝试使用Page.User.Identity.Name,它也返回空白.

有谁知道这是为什么以及如何解决它?

小智 15

您可能已启用匿名身份验证以及Windows身份验证.关闭匿名关闭.

所以,

<system.web>
    <authentication mode="Windows" />
</system.web>
Run Code Online (Sandbox Code Playgroud)

在应用程序的IIS配置中,查看"身份验证"选项卡

Set **Anonymous Authentication** to **Disabled** and
Set **Windows Authentication** to **Enabled**
Run Code Online (Sandbox Code Playgroud)

这应该工作,Identity.UserName现在应该正确显示.


小智 0

对于空白返回,我的解决方案最终是 web.config。我使用的是 Visual Studio 2010,默认的 web.config 不起作用。我用几乎空的 web.config 替换它,然后成功了!也许默认的 vs2010 web.config 调用了太多引用,或者错误地配置了 IIS 以使用 User.Identity.Name。我的系统是Windows7。

vs2010 中的默认 asp.net 网站 web.config 大约有 100-115 行长。正如您在下面看到的,几乎空的 web.config 大约有 20 行长。


我使用的 web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <system.web>
   <authentication mode="Windows" />
   <authorization>
      <allow roles="Doman Name\Group Name" users="" />
      <deny users="*" />
   </authorization>

  </system.web>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
        <security>
            <authorization>
                <add accessType="Allow" users="" roles="Doman Name\Group Name" />
            </authorization>
        </security>
  </system.webServer>

</configuration>
Run Code Online (Sandbox Code Playgroud)