Charandeep Singh Charandeep Singh - 3 months ago 26
C# Question

NullReferenceException while using Authorize Attribute

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.

Answer

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.

Comments