NullReference exception when using Authorize attribute

I have the [Authorize] attribute on the HomeController , whenever I try to access it, it throws a NullReferenceException

This is really strange because I used [Authorize] many times before and it works great. The only difference in this case is that this application is hosted on our own web server using Windows 7 and IIS 7.5

Here is the stack trace:

[NullReferenceException: object reference not set to instance object.]
System.Web.Mvc.AuthorizeAttribute.AuthorizeCore (HttpContextBase httpContext) +38
System.Web.Mvc.AuthorizeAttribute.OnAuthorization (AuthorizationContext filterContext) +160
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters (ControllerContext controlContext, IList`1, ActionDescriptor actionDescriptor) +155
System.Web.Mvc.ControllerActionInvoker.InvokeAction (ControllerContext controllerContext, String actionName) +784976
System.Web.Mvc.Controller.ExecuteCore () +159
System.Web.Mvc.ControllerBase.Execute (RequestContext requestContext) +335 System.Web.Mvc. <> c_DisplayClassb.b_5 () +62
System.Web.Mvc.Async. <> c_DisplayClass1.b_0 () +20
System.Web.Mvc. <> c_DisplayClasse.b_d () +54
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute () +453 System.Web.HttpApplication.ExecuteStep (step IExecutionStep, Logical & completed synchronously) +371

Edit:

Studying the code of the AuthorizeCore method, it seems that AuthorizeCore throws a NullReferenceException because it gets a NULL HttpContextBase .

Is it possible? Since everything else in the application works very well, for example, accessing the database, creating cookies, etc.

Edit 2:

This only happens after publishing to the web server. Although development, it works great with Visual Studio.

+7
source share
3 answers

The problem was even worse: HttpContext was not even available in Controller and Razor views. So, I am reinstalling ASP.NET v4.0 using aspnet_regiis -ir . And then used the ASP.NET 4.0 pool that was created during registration, instead of using DefaultAppPool .

And he began to work normally . It also solves my other problem of overriding <modules runAllManagedModulesForAllRequests="true"/> in my web.config application.

+4
source

In my case, I set HttpContext.Current.User to null in one of the events of the global.asax application. When I made the User property unchanged, the error disappeared.

+1
source

You probably need to make sure that the application pool used by your site has a managed route = classic mode.

0
source

All Articles