Why am I getting a NullReferenceException from Membership.GetCurrentUserName?

六月ゝ 毕业季﹏ 提交于 2019-12-08 02:20:37

问题


I've just switched to using msbuild to precompile my website and now I'm getting this strange error:

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
...

回答1:


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 is not null, and

  • HttpContext.Current.User is null or has a null Identity property.

All other paths seem to have a test for null.

So I suggest you trace the type and contents of HttpContext.User.

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.



来源:https://stackoverflow.com/questions/663018/why-am-i-getting-a-nullreferenceexception-from-membership-getcurrentusername

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!