为什么我从Membership.GetCurrentUserName得到NullReferenceException? [英] Why am I getting a NullReferenceException from Membership.GetCurrentUserName?
问题描述
我刚改用msbuild来预编译我的网站,现在我遇到了这个奇怪的错误:
I've just switched to using msbuild to precompile my website and now I'm getting this strange error:
我有一个对Membership.GetUser()的调用,它引发:
I have a call to Membership.GetUser() which throws:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Security.Membership.GetCurrentUserName() +36
System.Web.Security.Membership.GetUser() +7
...
推荐答案
Reflector显示Membership.GetCurrentUserName的实现是:
Reflector shows the implementation of Membership.GetCurrentUserName is:
private static string GetCurrentUserName()
{
if (HostingEnvironment.IsHosted)
{
HttpContext current = HttpContext.Current;
if (current != null)
{
return current.User.Identity.Name;
}
}
IPrincipal currentPrincipal = Thread.CurrentPrincipal;
if ((currentPrincipal != null) && (currentPrincipal.Identity != null))
{
return currentPrincipal.Identity.Name;
}
return string.Empty;
}
乍一看,最可能的解释是:
At first glance the most likely explanation is that:
-
HttpContext.Current不为null,并且
HttpContext.Current is not null, and
HttpContext.Current.User为null或具有空的Identity属性.
HttpContext.Current.User is null or has a null Identity property.
所有其他路径似乎都对null进行了测试.
All other paths seem to have a test for null.
所以我建议您跟踪HttpContext.User的类型和内容.
So I suggest you trace the type and contents of HttpContext.User.
HttpContext.Current.User是一个IPrincipal,我所知道的IPrincipal的大多数具体实现都不允许使用null身份,因此我押注HttpContext.User为null.
HttpContext.Current.User is an IPrincipal, and most concrete implementations of IPrincipal that I know of don't allow a null identity, so I'd bet on HttpContext.User being null.
这篇关于为什么我从Membership.GetCurrentUserName得到NullReferenceException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!