ASP.NET MVC:IPrincipal 怎么可能为空?
我正在 IIS6/Server 2003 上运行一个网站,该网站在本地 Intranet 上使用集成 Windows 身份验证。我可以浏览到该站点,但在调用以下 C# 代码(每次请求时都会调用该代码)时会出现间歇性“对象为空”错误:
....
GetUserIdFromPrincipal(User)
....
public static string GetUserIdFromPrincipal(IPrincipal principal) {
return principal.Identity is WindowsIdentity ? (principal.Identity as WindowsIdentity).User.Value : principal.Identity.Name;
}
因此,由于该错误是间歇性的,所以 Windows Auth 显然在某种程度上正在工作,但在站点中导航了几个之后单击我收到空引用错误,这意味着 IPrincipal 为空(我认为这在 ASP.NET 中永远不应该为空)。
该错误仅发生在新建的虚拟机上。该代码在其他机器上运行良好,在本地开发时当然也运行良好。
IIS 是否在每次请求时都请求 Windows 身份验证详细信息?什么会导致这种间歇性问题?任何帮助或建议将不胜感激。
I'm running a website on IIS6 / Server 2003 which uses Integrated Windows Authentication on a local intranet. I can browse to the site but get intermittent "Object null" errors when calling the following C# code, which is called on every request:
....
GetUserIdFromPrincipal(User)
....
public static string GetUserIdFromPrincipal(IPrincipal principal) {
return principal.Identity is WindowsIdentity ? (principal.Identity as WindowsIdentity).User.Value : principal.Identity.Name;
}
So as the error is intermittent clearly Windows Auth is working on some level but after navigating around the site for several clicks I get the null reference error meaning IPrincipal is null (I thought this should never be null in ASP.NET).
The error only happens on a newly built VM. The code is fine on other machines and certainly when developing locally.
Does IIS request the Windows Auth details on each request? What would cause such an intermittent problem? Any help or suggestions would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议,您的身份根本不是 WindowsIdentity,因此该案例将失败并导致空对象。 IIdentity 可能是 FormsIdentity、ClientFormsIdentity、GenericIdentity、PassportIdentity 和 WindowsIdentity,我想您应该尝试
获取真正的 Identity。
I would suggest, that your Identity is simply not a WindowsIdentity and therefore the case will fail and leed to a null-object. IIdenty might be FormsIdentity, ClientFormsIdentity, GenericIdentity, PassportIdentity and WindowsIdentity, I guess you should try
to get the real one.
我认为在上面的情况下,这是因为我们在 IIS6 中检查了 Windows Auth 和 Anonymous。这似乎造成了这样的情况:IIS 有时会使用 Windows Auth,从而创建 IPrincipal,但有时会使用匿名身份验证,而不会创建 IPrinciple。当然,关闭“匿名身份验证”选项似乎已经解决了问题。
I think in the case above it was because we had Windows Auth and Anonymous checked in IIS6. This seemed to create the situation that IIS would sometimes use Windows Auth and hence create an IPrincipal but other times would use Anonymous Auth which would not create an IPrinciple. Certainly turning off the Anonymous Auth option seems to have resolved the problem.