【问题标题】:"cannot set status after HTTP headers" when overriding AuthorizeAttribute.AuthorizeCore覆盖 AuthorizeAttribute.AuthorizeCore 时“无法在 HTTP 标头之后设置状态”
【发布时间】:2011-10-13 11:23:12
【问题描述】:

我正在尝试在 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;
}

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

一切正常,但每当AuthorizeCore 返回false MVC 继续处理请求并调用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)

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

【问题讨论】:

    标签: .net asp.net asp.net-mvc iis


    【解决方案1】:

    我遇到了类似的问题(我需要重定向),下面修复了我的问题

    1. 我使用了 OnAuthorization 覆盖
    2. 当我不得不重定向时做了以下操作

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

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

    【讨论】:

      【解决方案2】:

      请在此处查看答案:Extend AuthorizeAttribute Override AuthorizeCore or OnAuthorization

      您不应在 AuthorizeCore 中设置标头并结束响应,作为其“决策代码”

      重写 OnAuthorization 以添加标题等

      编辑: 为了防止MVC继续处理请求,需要设置OnAuthorization中的FilterContext.Result。

      编辑: 您最终可能会得到一个 CustomError。 如果是,请添加以下内容:

      HttpContext.Response.TrySkipIisCustomErrors(true)
      

      【讨论】:

      • 我仍然无法停止请求处理 - 它继续到 FormsAuthenticationModule.OnLeave(),后者继续到 HttpResponse.Redirect(),我得到了与最初相同的错误,因为我已经结束了响应。
      • 好的,试试 context.ApplicationInstance.CompleteRequest() 而不是 Response.End()
      • 编辑:另外,意思是覆盖 OnAuthoirization,而不是 OnAuthorize
      • cacheandquery.com/blog/2011/03/… 给出一个完整的实现。我偷偷地怀疑您还需要设置 filtercontext.result 以进一步停止请求处理。
      • 难以置信 - 我在 OnAuthorization() 内部调用 CompleteRequest() 并且未经授权的请求进一步传递。
      猜你喜欢
      • 2014-01-27
      • 2012-09-28
      • 1970-01-01
      • 2011-01-23
      • 2015-11-07
      • 1970-01-01
      • 2016-03-19
      • 2019-07-22
      • 2016-08-27
      相关资源
      最近更新 更多