我有一个在某些情况下被抛出的自定义异常。当它被抛出时,我想渲染一个特定的视图并将其输出到响应。
在开始之前,是的,我在根级Web.config中有<customErrors mode="On" />
。
我几乎完全按照Darin在this answer中提出的建议:
public class EntityNotFoundHandleErrorAttribute : HandleErrorAttribute {
public override void OnException(ExceptionContext filterContext) {
if (!filterContext.IsChildAction && !filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled && filterContext.Exception is EntityNotFoundException) {
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
ViewResult result = new ViewResult {
ViewName = this.View,
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
filterContext.Result = result;
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
}
并在FilterConfig.cs中注册(从Global.asax调用):
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new EntityNotFoundHandleErrorAttribute() {
ExceptionType = typeof(Inspect.Models.EntityNotFoundException),
View = "NotFound",
Order = 2
});
// Commented out just to be sure this isn't screwing it up.
// filters.Add(new Utilities.ElmahHandleErrorAttribute(), 1);
}
这笔交易是,我可以确认OnException
正在按预期运行,但视图没有显示。相反,我得到黄色死亡屏幕的无用版本,告诉我如果我想查看详细信息,我应该使用customErrors="RemoteOnly"
。
如果我将filterContext.Result
更改为RedirectResult
,那么所有这些内容都有效。但我不想这样做。我只想将视图写入响应。
答案 0 :(得分:0)
this.View
的值为"NotFound"
。将其更改为"~/Views/Errors/NotFound"
可以解决问题。