如何在IIS 10上使用C#Razor获取Windows用户域/用户名?

尝试构建一个Web应用程序,该应用程序将使用Windows身份验证与Active Directory进行单点登录 . 我无法获取登录的Windows用户域和用户名 . 我尝试过的事情:

  • WindowsIdentity.GetCurrent().Name

返回 IIS APPPOOL\DefaultAppPool

  • System.Environment.UserName

返回 DefaultAppPool

  • Page.User.Identity.Name

导致编译错误

匿名身份验证已禁用
ASP.NET模拟已启用
Windows身份验证已启用

Web.config文件

<?xml version =“1.0”encoding =“utf-8”?>
<结构>
<的appSettings>
<add key =“EnableSimpleMembership”value =“false”/>
</的appSettings>
在<system.web>
<compilation debug =“false”targetFramework =“4.6.1”>
<组件>
<add assembly =“System.Net.Http,Version = 4.1.0.0,Culture = neutral,PublicKeyToken = B03F5F7F11D50A3A”/>
<add assembly =“Microsoft.Web.Administration,Version = 7.0.0.0,Culture = neutral,PublicKeyToken = 31BF3856AD364E35”/>
</组件>
</汇编>

<httpRuntime targetFramework =“4.6.1”/> <authentication mode =“Windows”/> <授权> <deny users =“?” /> </授权> <identity impersonate =“true”/> </system.web> <运行> <assemblyBinding xmlns =“urn:schemas-microsoft-com:asm.v1”> <dependentAssembly> <assemblyIdentity name =“System.Security.Cryptography.X509Certificates”publicKeyToken =“b03f5f7f11d50a3a”culture =“neutral”/> <bindingRedirect oldVersion =“0.0.0.0-4.1.0.0”newVersion =“4.1.0.0”/> </ dependentAssembly> <dependentAssembly> <assemblyIdentity name =“Microsoft.Win32.Primitives”publicKeyToken =“b03f5f7f11d50a3a”culture =“neutral”/> <bindingRedirect oldVersion =“0.0.0.0-4.0.1.0”newVersion =“4.0.1.0”/> </ dependentAssembly> <dependentAssembly> <assemblyIdentity name =“System.Net.Http”publicKeyToken =“b03f5f7f11d50a3a”culture =“neutral”/> <bindingRedirect oldVersion =“0.0.0.0-4.1.0.0”newVersion =“4.1.0.0”/> </ dependentAssembly> <dependentAssembly> <assemblyIdentity name =“Newtonsoft.Json”publicKeyToken =“30ad4fe6b2a6aeed”culture =“neutral”/> <bindingRedirect oldVersion =“0.0.0.0-9.0.0.0”newVersion =“9.0.0.0”/> </ dependentAssembly> </ assemblyBinding> </运行> <system.webServer> <modules runAllManagedModulesForAllRequests =“true”> </模块> <validation validateIntegratedModeConfiguration =“false”/> <处理程序> <remove name =“ExtensionlessUrlHandler-Integrated-4.0”/> <remove name =“OPTIONSVerbHandler”/> <remove name =“TRACEVerbHandler”/> <add name =“ExtensionlessUrlHandler-Integrated-4.0”path =“* . ” verb =“*”type =“System.Web.Handlers.TransferRequestHandler”preCondition =“integratedMode,runtimeVersionv4.0”/> </搬运车> </system.webServer> </配置>

回答(2)

2 years ago

您可能需要进行调整,具体取决于您尝试访问当前用户的 context

例如从 Controller 您可以执行以下操作:

User.Identity.GetUserId();

确保您使用的是:

using Microsoft.AspNet.Identity;

2 years ago

请尝试以下方法:

var windowsIdentity = System.Web.HttpContext.Current.User.Identity as WindowsIdentity;