我管理我的所有应用程序错误Application_Error()
in 全局.asax:
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()
被调用,但如此直接调用异常对我来说似乎很难看,是否存在另一种方式?你们觉得怎么样?
因为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");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)