[英].Net Mvc: How to fire a error for Application_Error() manage them?
我在Global.asax的 Application_Error()
中管理所有应用程序错误:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Log.LogException(exception);
Response.Clear();
HttpException httpException = exception as HttpException;
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Erro");
if (httpException == null)
{
routeData.Values.Add("action", "Index");
}
else //It's an Http Exception
{
switch (httpException.GetHttpCode())
{
case 404:
//Page not found
routeData.Values.Add("action", "HttpError404");
break;
case 500:
//Server error
routeData.Values.Add("action", "HttpError500");
break;
// Here you can handle Views to other error codes.
// I choose a General error template
default:
routeData.Values.Add("action", "General");
break;
}
}
//Pass exception details to the target error View.
routeData.Values.Add("error", exception);
//Clear the error on server.
Server.ClearError();
//Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
//Call target Controller and pass the routeData.
IController errorController = new ErroController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
因此,我在我的应用程序中具有一个自定义授权属性,该属性可以处理未经授权的请求,并且我想重定向到Application_Error()
处理。
因此,我这样做:
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
if (context.HttpContext.Request.IsAuthenticated)
{
throw new HttpException(403, "Forbidden Access.");
}
else
{
base.HandleUnauthorizedRequest(context);
}
}
通过这种方式调用Application_Error()
,但是对我来说直接调用异常似乎很丑,所以存在另一种方式吗? 你觉得男人呢?
您不应在AuthorizeAttribute内部引发异常,因为这可能导致依赖AuthorizeAttribute进行授权检查的代码出现性能问题。 AuthorizeAttribute用于检查授权是否有效,而不是根据此信息采取的措施。 这就是为什么原始代码不会直接引发异常的原因-它会将任务委托给HttpUnauthorizedResult类。
相反,您应该创建一个自定义处理程序(类似于HttpUnauthorizedResult )以引发异常。 这将把检查授权和基于未授权采取行动的逻辑明确地分为两个不同的类别。
public class HttpForbiddenResult : HttpStatusCodeResult
{
public HttpForbiddenResult()
: this(null)
{
}
// Forbidden is equivalent to HTTP status 403, the status code for forbidden
// access. Other code might intercept this and perform some special logic. For
// example, the FormsAuthenticationModule looks for 401 responses and instead
// redirects the user to the login page.
public HttpForbiddenResult(string statusDescription)
: base(HttpStatusCode.Forbidden, statusDescription)
{
}
}
然后在自定义的AuthorizeAttribute中,只需在HandleUnauthorizedRequest中设置新的处理程序。
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
if (context.HttpContext.Request.IsAuthenticated)
{
// Returns HTTP 403 - see comment in HttpForbiddenResult.cs.
filterContext.Result = new HttpForbiddenResult("Forbidden Access.");
}
else
{
base.HandleUnauthorizedRequest(context);
}
}
如果您需要执行与抛出HttpException不同的操作,则应将ActionResult子类化并在ExecuteResult方法中实现该操作,或使用继承ActionResult的内置类之一。
因为默认情况下, Unauthorized
不是错误 !!! 只需将此方法添加到global.asax
protected void Application_EndRequest(object sender, EventArgs e) {
if (Context.Response.StatusCode == 401 || Context.Response.StatusCode == 403) {
// this is important, because the 401 is not an error by default!!!
throw new HttpException(401, "You are not authorised");
}
}
您的代码很好。 默认情况下,如果您调用base.HandleUnauthorizedRequest
它将抛出401
异常,该异常会被表单身份验证模块拦截,然后您将被重定向到登录页面(这可能不是所需的行为)。 所以你的方法是正确的。
另一种可能性是,如果您不想通过Application_Error
,则直接呈现相应的错误视图:
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
if (context.HttpContext.Request.IsAuthenticated)
{
context.Result = new ViewResult
{
ViewName = "~/Views/Shared/Forbidden.cshtml"
};
}
else
{
base.HandleUnauthorizedRequest(context);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.