【问题标题】:HttpContext.User NullReferenceException only on deployed serverHttpContext.User NullReferenceException 仅在部署的服务器上
【发布时间】:2015-03-11 16:03:07
【问题描述】:

我在我的 MVC 项目中使用表单身份验证,当使用 Visual Studio 开发服务器进行本地测试时,一切都按预期工作。一旦部署到 IIS 7.5,HTTPContext.User 就会导致 NullReferenceExceptions。

Dev 和 Prod 机器都使用相同的 SQL db(目前 - 这当然会在部署后改变)所以我知道这不是数据库或其中的数据的问题。

这必须是 IIS 或我的 web.config 中的设置,但我找不到。 我已经尝试对我的 web.config 进行各种更改(来自我在 SE 周围找到的建议),这是我当前实现的 web.config 的一部分:

<appSettings>
    <add key="autoFormsAuthentication" value="true" />
    <add key="enableSimpleMembership" value="false" />
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />

****截图****

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="X-UA-Compatible" value="IE=9" />
      </customHeaders>
    </httpProtocol>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <modules runAllManagedModulesForAllRequests="false">

      <remove name="FormsAuthentication" />
      <remove name="DefaultAuthentication" />
      <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="" />
      <add name="DefaultAuthentication" type="System.Web.Security.DefaultAuthenticationModule" preCondition="" />

      <remove name="UrlRoutingModule-4.0"/>
      <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" preCondition="" />
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
    </modules>
  </system.webServer>

什么可能导致HttpContext.User 与 VS 开发服务器和 IIS 7.5 实现不同?

编辑:

HttpContext 是通过继承的 BaseController 提供的:

protected virtual new CustomPrincipal User
{
    get { return HttpContext.User == null? null : HttpContext.User as CustomPrincipal; }
}

public new HttpContextBase HttpContext
{
    get
    {
        return ControllerContext == null ? null : ControllerContext.HttpContext;
    }
}

在 PostAuthenticationRequest 之前不会创建 cookie:

 public void MvcApplication_PostAuthenticationRequest(object sender, EventArgs e)
{

    var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {

        string encTicket = authCookie.Value;
        if (!String.IsNullOrEmpty(encTicket))
        {

            var ticket = FormsAuthentication.Decrypt(encTicket);
            var id = new UserIdentity(ticket);
            string[] userRole = Roles.GetRolesForUser(id.Name);
            var prin = new CustomPrincipal(id);
            HttpContext.Current.User = prin;
            Thread.CurrentPrincipal = prin;
        }
    }
}

身份验证本身似乎工作正常,因为导致异常的函数以[Authorize] 开头并成功开始执行,但在到达第一个用户引用时失败为null

int userT = User.Team.TeamId;

在这种情况下,用户是 CustomPrincipal BaseController.User

EDIT2:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" 
         cookieless="UseCookies"
         name=".ASPXAUTH"
         protection="All"
         slidingExpiration="true"/>
</authentication>

EDIT3

自定义IIdentity:

 [Serializable]
    public class UserIdentity : MarshalByRefObject, IIdentity
    {
        private readonly FormsAuthenticationTicket _ticket;


        public UserIdentity(FormsAuthenticationTicket ticket)
        {
            _ticket = ticket;
        }

        public string AuthenticationType
        {
            get { return "Custom"; }
        }

        public bool IsAuthenticated
        {
            get { return !string.IsNullOrEmpty(this.Name); }
        }

        public string Name
        {
            get { return _ticket.Name; }
        }

        public string UserId
        {
            get { return _ticket.UserData; }
        }

        public bool IsInRole(string Role)
        {
            return Roles.IsUserInRole(Role);
        }

        public IIdentity Identity
        {
            get { return this; }
        }


public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        if (context.State == StreamingContextStates.CrossAppDomain)
        {
            GenericIdentity gIdent = new GenericIdentity(this.Name, this.AuthenticationType);
            info.SetType(gIdent.GetType());

            System.Reflection.MemberInfo[] serializableMembers;
            object[] serializableValues;

            serializableMembers = FormatterServices.GetSerializableMembers(gIdent.GetType());
            serializableValues = FormatterServices.GetObjectData(gIdent, serializableMembers);

            for (int i = 0; i < serializableMembers.Length; i++)
            {
                info.AddValue(serializableMembers[i].Name, serializableValues[i]);
            }
        }
        else
        {
            throw new InvalidOperationException("Serialization not supported");
        }
    }

自定义IPrincipal:

interface ICustomPrincipal : IPrincipal
{
    int Id { get; set; }
    string Name { get; set; }
    string Role { get; set; }
}

public class CustomPrincipal : IPrincipal
{
    public CustomPrincipal(UserIdentity identity)
    {
        this.Identity = identity;
    }

    public IIdentity Identity { get; private set; }

【问题讨论】:

  • 项目是否有无扩展页面?在这种情况下,设置 runAllManagedModulesForAllRequests=true 可能会有所帮助。也许这个链接会帮助forums.asp.net/t/…
  • @PankajKumar 谢谢,这确实解决了它,但我在其他地方看到这不是解决任何问题的正确方法。有没有更好的替代品?
  • 您似乎正在实施自己的身份验证,那么您是否也使用/实施了FilterAttributes?为什么你忽略了IPrincipal 这样的接口?似乎您正在使用 WebForms 和 MVC 的组合!这些使问题更难解决。
  • stackoverflow.com/questions/13343073/… 可能会对您有所帮助,因为您的部署区域在 machinekey 配置中有所不同,而在本地您可以忽略此类选项,因为它在顶级配置文件中使用了一个选项。
  • CustomPrincipal 是一个 IPrincipal。附言当您对问题进行评分时,最好留下解释。

标签: asp.net-mvc-4 iis iis-7.5 forms-authentication nullreferenceexception


【解决方案1】:

很可能,您正试图在初始化之前检索HttpContext.User。这种行为在 IIS 经典(或 Visual Studio Web 服务器)和 IIS 集成管道模式之间有所不同,这可以解释为什么您会看到不同环境之间的行为。

说明

HttpContext 是应用程序运行时状态的一部分。在现代托管环境(IIS 集成管道模式和 OWIN)中,HttpContext 直到 Application_Start 方法完成后才会填充。任何需要HttpContext.User 的行为都不应在Application_BeginRequest 事件或之后执行。

参考:Request is not available in this context

【讨论】:

  • 但是此时 Application_Start 应该已经被触发了,对吗?我的控制器工厂在 Application_Start 中启动,直到经过身份验证后数据才会被删除。
  • 好吧,您还没有在应用程序中发布您收到错误的位置,所以这有点在黑暗中拍摄。但症状很合适。如果使用 DI,您是否在访问您的一项服务的构造函数的调用堆栈中的 HttpContext.User 属性?请注意,您不能这样做。解决方案见this answer
  • 请注意,您可以通过将本地环境设置为在 IIS 集成模式下运行来证明或反驳这一理论。如果这导致您的开发环境中发生错误,那么您可以更轻松地追踪问题。
  • 我在 VS 开发服务器上找到的所有信息都表明它无法切换到集成管道。你知道切换它的方法吗?
  • 您需要将其临时托管在本地 IIS 下才能启用集成模式(在应用程序池中)。 VS 开发服务器没有这个选项。
【解决方案2】:

您的帖子并不清楚,因为配置身份验证取决于项目中的各种设置以及配置文件。例如,在 Web.config 文件中,有几个地方可以自定义/配置身份验证,例如您未在帖子中放置的这条(最重要的规则):

<system.web>
   <authentication mode="" />
</system.web>

如您所知,由于配置系统是基于使用 **.config* 文件的管理系统的分层系统,您应该考虑默认值,可能通过&lt;remove/&gt;&lt;add/&gt; 一些参数。 IIS 7 及更高版本的配置文件位于您的%WinDir%\System32\Inetsrv\Config 文件夹中,主要配置文件是:

  • ApplicationHost.config - 此配置文件存储您所有网站和应用程序的设置。
  • Administration.config - 此配置文件存储 IIS 管理的设置。这些设置包括 为 IIS 管理器工具安装的管理模块,如 以及管理模块的配置设置。
  • Redirection.config - IIS 7 及更高版本支持从一个集中的配置文件管理多个 IIS 服务器。 此配置文件包含指示 存储集中配置文件的位置。

注意:某些设置可以委托给 Web.config 文件,这可能会覆盖 ApplicationHost.config 文件中的设置。此外,未委托的设置无法添加到 Web.config 文件中。

提示:IIS 7 的默认安装不包含 Digest 身份验证,因此将 Digest 身份验证设置添加到您的 ApplicationHost.config 将无效或可能导致在安装 Digest 身份验证模块之前出现错误。

您需要查看本地和部署配置以满足您的目的。如果您在使用集成管道时遇到问题,请参阅以下页面以利用其优势:

更新关于 SlidingExpiration:根据MSDN

滑动到期重置有效时间的到期时间 身份验证 cookie,如果发出请求并且超过一半 超时间隔已过。

如果 cookie 过期,用户必须重新验证。将SlidingExpiration 属性设置为false 可以通过根据配置的超时值限制身份验证cookie的有效时间来提高应用程序的安全性。 所以我认为有无需将其用作false。这意味着如果在此时间段内没有任何请求,它将在激活缓存时的时间段后过期缓存。 当有很多数据要缓存时,这种类型的过期非常有用。 所以它会将那些在应用程序中经常使用的项目放入缓存中。所以它不会使用不必要的内存。

【讨论】:

  • 将我的身份验证模式设置添加为 Edit2。
  • @GamerJ5 我也更新了我的答案,但是我们需要更完整的细节来解决这个问题,比如 有用 堆栈跟踪等等......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 2013-04-13
  • 2016-11-27
  • 2018-06-13
相关资源
最近更新 更多