forms-authentication - 授权时 ASP.NET MVC5 应用程序抛出 NullReferenceException

标签 forms-authentication asp.net-mvc-5 httpmodule

我有一个 MVC5 应用程序在使用 [Authorize] 时在生产服务器上抛出 NullReferenceException Controller 上的属性。该应用程序正在使用表单例份验证。

生产服务器是 Server 2008 SP 2(.NET 4.5.1 和 IIS 7)。

堆栈跟踪的开始是:

[NullReferenceException: Object reference not set to an instance of an object.]
   System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +38
   System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +293
   System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +155

我可以通过设置来修复它
<modules runAllManagedModulesForAllRequests="true">

但是,我不喜欢使用这样的 sledgehammer method .

有没有更清洁的方法来解决这个问题?

最佳答案

IIS 和 IIS Express 对请求身份验证有一些不同的行为。 HttpContext.User.Identity AuthorizeAttribute.AuthorizeCore() 时属性可能不被设置。方法执行(因此 NullReferenceException ),因为身份验证模块并不总是运行。

您可以仅更改您需要的身份验证模块的前提条件,而不是为所有请求加载所有模块。例如,FormsAuthenticationModule 有:preCondition="managedHandler"默认情况下。

<system.webServer>
  <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="" />
  </modules>
</system.webServer>

关于forms-authentication - 授权时 ASP.NET MVC5 应用程序抛出 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21170269/

相关文章:

c# - 表单例份验证不适用于特定页面

asp.net - 使用表单例份验证模拟

ruby - 什么是 Sinatra/Rack 的非常简单的身份验证方案

javascript - Jquery UI、Razor 和 MVC : Uncaught TypeError: Illegal invocation

回调时 Facebook OAuth LoginInfo 为空

c# - 从 HTTPModule 访问 session 变量

c# - 缺少 ASP.net MVC FormsAuthentication cookie

asp.net-core - 使用 FromBody 的路由不适用于 ASP.NET Core

javascript - 如何获取当前页面中 Referer 页面的值(该页面中的隐藏字段)?

sharepoint - HttpModule 事件 - 拦截共享点重定向到 accessdenied.aspx