.Net Mvc: ¿Cómo activar un error para Application_Error () administrarlos?
Administro todos los errores de aplicación en miApplication_Error()
in Global.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));
}
Por lo tanto, tengo un atributo de autorización personalizado en mi aplicación que maneja la solicitud no autorizada y quiero redirigir aApplication_Error()
manipule eso en su lugar.
Entonces, yo hago eso:
p,rotected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
if (context.HttpContext.Request.IsAuthenticated)
{
throw new HttpException(403, "Forbidden Access.");
}
else
{
base.HandleUnauthorizedRequest(context);
}
}
De esa manera elApplication_Error()
se llama, pero me parece feo llamar a una excepción tan directamente, ¿existe otra forma? ¿Qué les parece chicos?