ASP.NET MVC5 application throwing NullReferenceException when authorizing

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

I have an MVC5 application that is throwing a NullReferenceException on the production server when using the [Authorize] attribute on a controller. The application is using forms authentication.

The production server is Server 2008 SP 2 (.NET 4.5.1 and IIS 7).

The start of the stack trace is:

[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 

I can fix it by setting

<modules runAllManagedModulesForAllRequests="true"> 

However, I prefer not to use such a sledgehammer method.

Is there a cleaner way of fixing this problem?

回答1:

IIS and IIS Express have some differing behaviors for request authentication. The HttpContext.User.Identity property may not be set when the AuthorizeAttribute.AuthorizeCore() method executes (hence the NullReferenceException), due the fact that the authentication module does not always run.

You could change the precondition for only the authentication modules you need instead of loading all modules for all requests. For example, the FormsAuthenticationModule has: preCondition="managedHandler" by default.

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


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