【发布时间】:2019-03-13 23:18:43
【问题描述】:
我编写了一个自定义异常过滤器来记录我的应用程序异常 并且在异常之后我想将用户重定向到错误页面 下面是我的代码
我的代码工作得很好,它捕捉到了异常,但在记录后它并没有把我扔到错误页面,你能帮忙吗
我的 CustomException Filer 类
public class CustomExceptionFilterAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
try
{
string requestBody = "", Action = "", Controller = "";
try
{
requestBody = filterContext.HttpContext.Request.Form.ToString();
Action = filterContext.RouteData.Values["action"].ToString();
Controller = filterContext.RouteData.Values["controller"].ToString();
}
catch (Exception)
{
}
StringBuilder sbHeader = new StringBuilder();
sbHeader.AppendLine(filterContext.RequestContext.HttpContext.Request.Headers.ToString());
StaticMethods.LogException(SessionHelper.LoginCode.ToString(), Action, Controller, filterContext.Exception.Message, filterContext.RequestContext.HttpContext.Request.RawUrl.ToString(), requestBody, sbHeader.ToString());
// This is which i am more concern about
filterContext.RouteData.Values.Add("Error", filterContext.Exception.Message);
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Error", action = "Error" }));
}
catch(Exception ex)
{
}
}
}
这是我的错误控制器
public class ErrorController : Controller
{
// GET: Error
public ActionResult Error()
{
ViewBag["ErrorMessage"] = RouteData.Values["Error"];
return View();
}
}
这是我的 Error.cshtml
<div class="alert alert-danger">
<environment names="Development">
<strong>Error!</strong> Some Error Occured.
</environment>
<environment names="Staging,Production">
<strong>Error!</strong> @ViewBag.ErrorMessage
</environment>
</div>
有人可以帮忙吗 我只想在记录异常后重定向到错误页面 它仍然向我显示带有抛出错误的黄页
谢谢
【问题讨论】:
-
以下两个答案都是两种方法,您也可以使用 web.config 转换 stackoverflow.com/questions/5811305/web-config-debug-release 和后者
标签: c# asp.net exception-handling asp.net-mvc-5