重写AuthorizeAttribute.AuthorizeCore时,"无法在HTTP标头后设置状态"

sha*_*oth 3 .net asp.net iis asp.net-mvc

我正在尝试在MVC 2应用程序的特定控制器上实现自定义基本身份验证.具体来说,我继承AuthorizeAttribute并覆盖AuthorizeCore()方法:

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    if( doAuthorization() ) {
        return true;
    }
    // send HTTP 401
    HttpContext context = HttpContext.Current;
    context.Response.StatusCode = 401;
    context.Response.AddHeader( "WWW-Authenticate",
        String.Format("Basic realm=\"{0}\"", myRealm);
    context.Response.End();
    return false;
}
Run Code Online (Sandbox Code Playgroud)

并使用我的继承属性标记控制器.

整个过程都有效,但每当AuthorizeCore返回falseMVC继续处理请求并被Application_Error()调用时,我会在那里检索以下异常:

Server cannot set status after HTTP headers have been sent.
at System.Web.HttpResponse.set_StatusCode(Int32 value)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Run Code Online (Sandbox Code Playgroud)

如何让MVC停止处理请求并防止该异常?

Ram*_*esh 6

我遇到了类似的问题(我需要重定向)和下面固定的我的问题

  1. 我使用OnAuthorization覆盖
  2. 当我不得不重定向时,下面做了

    filterContext.Result = new HttpStatusCodeResult(System.Net.HttpStatusCode.Redirect); filterContext.HttpContext.Response.Redirect(url,false);

关键是填充filterContext.Result.如果填充了MVC框架,则不会调用action方法.