如何在新的ASP.NET MVC应用程序中创建基本控制器,该应用程序将包含样板代码,以处理派生控制器中每个操作的所有try / catch例程,并在登录到Nlog后返回标准JSON错误消息。我还想处理404错误以重定向到自定义404视图。我的目标是使用OWIN cookie身份验证,并希望在Cookie过期时注销。我的所有操作都将返回JsonResult并通过jQuery Ajax调用。
在之前的项目中,我使用了以下方法:
在Global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
Exception lastError = Server.GetLastError();
Server.ClearError();
var statusCode = 0;
statusCode = lastError.GetType() == typeof(HttpException) ? ((HttpException)lastError).GetHttpCode() : 500;
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("statusCode", statusCode);
routeData.Values.Add("exception", lastError);
if (new HttpRequestWrapper(HttpContext.Current.Request).IsAjaxRequest())
{
routeData.Values.Add("action", "Ajax");
}
else
{
routeData.Values.Add("action", "Index");
}
var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
IController controller = new ErrorController();
controller.Execute(requestContext);
Response.End();
}
在ErrorController.cs
public class ErrorController : Controller
{
public ActionResult Index(int statusCode, Exception exception)
{
var model = new ErrorModel { HttpStatusCode = statusCode, Exception = exception.Message };
Response.StatusCode = statusCode;
return View(model);
}
public JsonResult Ajax(int statusCode, Exception exception, Dictionary<string,string> validationErrors = null)
{
var model = new ErrorModel { HttpStatusCode = statusCode, Exception = exception.Message };
if (exception.GetType() == typeof (DbEntityValidationException))
{
model.ValidationErrors = null;
}
else
{
model.ValidationErrors = validationErrors;
}
Response.StatusCode = statusCode;
return Json(model, JsonRequestBehavior.AllowGet);
}
}
答案 0 :(得分:0)
最好的方法是将HandleErrorAttribute
扩展为:
public class AjaxAwareHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
// Execute the normal exception handling routine...
base.OnException(filterContext);
// Verify if AJAX request...
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// Use Json in case of AJAX request...
var result = new JsonResult();
result.Data = new { Error = filterContext.Exception.Message };
filterContext.Result = result;
}
}
}
然后,您需要做的就是在FilterConfig
类的App_Start
类下注册该属性,如下所示:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AjaxAwareHandleErrorAttribute());
}
}