ASP MVC OnException发送异常数据进行查看

时间:2015-10-28 12:15:13

标签: c# asp.net-mvc

我覆盖了我的控制器OnException方法。

    protected override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.ExceptionHandled)
        {
            return;
        }
        filterContext.Result = new ViewResult
        {
            ViewName = "ErrorPage",
        };
        filterContext.ExceptionHandled = true;
    }

这给了我我的观点没有任何麻烦。但是,我也希望能够将异常消息发送到视图。像这样:

ViewBag.Message = filterContext.Exception.Message;

然后在我看来:

@model System.Web.Mvc.HandleErrorInfo

@{
ViewBag.Title = "Error";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
<h2 class="text-danger">Error message: @ViewBag.Message</h2>

我可能错过了一些愚蠢的细节,但任何帮助都会受到赞赏!

更新:

原来我犯了一个大错。我已将重写的方法更改为下面的方法,现在我的ViewBag.Message也被发送到View。

    protected override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.ExceptionHandled)
        {
            return;
        }

        var ex = filterContext.Exception ?? new Exception("No further information exists.");

        ViewBag.Message = ex.Message;
        filterContext.Result = View("ErrorPage");

        filterContext.ExceptionHandled = true;
    }

0 个答案:

没有答案