我正在尝试在 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()
时,我会在那里检索以下异常: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 停止处理请求并防止该异常?
最佳答案
我遇到了类似的问题(我需要重定向),下面修复了我的问题
filterContext.Result = new HttpStatusCodeResult(System.Net.HttpStatusCode.Redirect);
filterContext.HttpContext.Response.Redirect(url, false);
关键是填充
filterContext.Result
。如果已填充,则 MVC 框架不会调用操作方法。关于.net - "cannot set status after HTTP headers"覆盖 AuthorizeAttribute.AuthorizeCore 时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7753368/