部署到IIS后WindowsIdentity.GetCurrent().Name返回NULL的问题求助
问题描述
我正尝试从Active Directory中获取数据,相关代码如下:
UserPrincipal up = UserADIdentity.GetADUserInfo(WindowsIdentity.GetCurrent().Name.ToString()); public static UserPrincipal GetADUserInfo(string userName) { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { UserPrincipal userPrincipal = new UserPrincipal(ctx); userPrincipal.SamAccountName = userName; userPrincipal.Enabled = true; userPrincipal = new PrincipalSearcher(userPrincipal).FindOne() as UserPrincipal; } }
该代码在本地计算机运行正常,但部署至服务器IIS后,WindowsIdentity.GetCurrent().Name.ToString()这行代码始终返回NULL。我的代码在ApplicationPoolIdentity身份下运行,报错截图如下:
原因分析
ApplicationPoolIdentity是IIS生成的虚拟本地账户,不属于域环境用户,没有对应的Active Directory身份标识,因此WindowsIdentity.GetCurrent()无法获取有效用户信息,最终返回null。本地运行正常是因为开发环境通常使用当前登录的域/本地用户身份执行程序,能正确拿到用户标识。
解决方案
1. 切换应用程序池身份为域用户
- 打开IIS管理器,找到目标应用程序池
- 右键选择「高级设置」,在「进程模型」→「标识」处选择「自定义账户」,点击「设置」
- 输入拥有AD访问权限的域账户账号和密码
- 重启应用程序池后,
WindowsIdentity.GetCurrent().Name即可获取该域用户的名称
2. 启用Windows身份验证(针对获取终端访问用户身份的场景)
如果业务需要获取访问网站的终端用户的AD身份,而非应用程序池身份:
- 在IIS中给目标网站启用「Windows身份验证」,关闭匿名身份验证
- 在web.config中配置身份验证模式:
<system.web> <authentication mode="Windows" /> <authorization> <deny users="?" /> <!-- 拒绝匿名访问 --> </authorization> </system.web>
- 改用
HttpContext.Current.User.Identity.Name获取当前访问用户的AD用户名,替换原代码中的WindowsIdentity.GetCurrent().Name
3. 代码中指定AD访问账户
若不想修改应用程序池身份,可在创建PrincipalContext时直接传入拥有AD访问权限的域账户信息:
// 替换为实际的域信息和账户凭证 string domain = "你的域名"; string adUsername = "域账户名"; string adPassword = "域账户密码"; using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain, adUsername, adPassword)) { UserPrincipal userPrincipal = new UserPrincipal(ctx); userPrincipal.SamAccountName = userName; userPrincipal.Enabled = true; userPrincipal = new PrincipalSearcher(userPrincipal).FindOne() as UserPrincipal; }
注意:账户密码需妥善保管,建议通过加密配置文件存储,禁止硬编码。
内容的提问来源于stack exchange,提问作者rimi
相关产品推荐
相关产品推荐

