gpt4 book ai didi

.net - 覆盖 AuthorizeAttribute.AuthorizeCore 时为 "cannot set status after HTTP headers"

转载 作者:行者123 更新时间:2023-11-30 23:58:10 24 4
gpt4 key购买 nike

我正在尝试在 MVC 2 应用程序的特定 Controller 上实现自定义基本身份验证。具体来说,我继承了 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;
}

并用我继承的属性标记 Controller 。

一切正常,但每当 AuthorizeCore 返回 false MVC 继续处理请求并调用 Application_Error() 时,我检索到以下内容那里有异常(exception):

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 停止处理请求并防止出现异常?

最佳答案

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

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

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

关键是填充 filterContext.Result。如果填充 MVC 框架未调用操作方法。

关于.net - 覆盖 AuthorizeAttribute.AuthorizeCore 时为 "cannot set status after HTTP headers",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7753368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com