ASP.NET应用程序MVC5抛出的NullReferenceException授权时 [英] ASP.NET MVC5 application throwing NullReferenceException when authorizing

查看:656
本文介绍了ASP.NET应用程序MVC5抛出的NullReferenceException授权时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用一个控制器上的 [授权] 属性时的生产的服务器上抛出一个NullReferenceException的MVC5应用程序。该应用程序是使用窗体身份验证。

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.

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

The production server is Server 2008 SP 2 (.NET 4.5.1 and 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

我可以通过设置修复

I can fix it by setting

<modules runAllManagedModulesForAllRequests="true">

不过,我preFER不使用这样的的大锤方法

是否有解决这个问题的一个更清洁的方式?

Is there a cleaner way of fixing this problem?

推荐答案

IIS和IIS防爆preSS对请求验证一些不同的行为。在 HttpContext.User.Identity 财产不得设定当 AuthorizeAttribute.AuthorizeCore()方法执行(因此的NullReferenceException ),由于这一事实的认证模块并不总是运行。

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.

您可以改变precondition只需要而不是加载所有模块的所有请求的认证模块。例如,FormsAuthenticationModule有: preCondition =managedHandler默认

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>

这篇关于ASP.NET应用程序MVC5抛出的NullReferenceException授权时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆