8
votes

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

This is really kind of weird, because I have used [Authorize] many times before and it works just fine. Only difference in this case is this Application is hosted on our own Web Server using Windows 7 & IIS 7.5

Here is Stack Trace:

[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) +160
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, 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(IExecutionStep step, Boolean& completedSynchronously) +371

Edit:

While looking into code of AuthorizeCore method, it seems that AuthorizeCore is throwing NullReferenceException because it gets a NULL HttpContextBase.

Could it be possible? Because everything else in application is working just fine, like accessing database, creating auth cookie etc.

Edit 2:

This happen only after publishing it to Web Server. While development, it works absolutely fine from Visual Studio.

3
I got this exception because of an invalid cookie. If you experience this as well, try to open the developer tools in your browser, go to the "Resources" tab or similar, and delete all cookies related to the site. When you reload the page, it might work. :-)Patrick

3 Answers

4
votes

Issue was even more worse HttpContext was not even available in Controller's and Razor views. So, I reinstall ASP.NET v4.0 using aspnet_regiis -ir. And then used ASP.NET 4.0 pool which was created during registration instead of using DefaultAppPool.

And it started working fine. It also solve my another issue of overriding <modules runAllManagedModulesForAllRequests="true"/> in my application web.config.

1
votes

In my case I was setting HttpContext.Current.User to null in one of the global.asax application events. When I let the User property unchanged the error disappeared.

0
votes

You probably need to make sure that the application pool your site is using has Managed Pipeline Mode = Classic.