如何在MVC 5中将错误信息传递给错误视图?

5

我正在处理异常,并编写了以下代码。

Web.Config

<customErrors mode="On"></customErrors>

代码更改

public class CustomExceptionFilter : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {

        //_logger.Error("Uncaught exception", filterContext.Exception);

        ViewResult view = new ViewResult();
        view.ViewName = "Error";
        filterContext.Result = view;

        // Prepare the response code.
        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}

Global.asax

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    // To handle exceptions
    GlobalFilters.Filters.Add(new CustomExceptionFilter());

    var unityContainer = ModelContainer.Instance;
    DependencyResolver.SetResolver(new UnityDependencyResolver(unityContainer));
}

错误视图

@*@model System.Web.Mvc.HandleErrorAttribute*@
<div class="row">
    <div class="col-sm-12">
        <h1>Error</h1>
        <div class="col-sm-12">
            <h2>An error occurred while processing your request.</h2>
        </div>
    </div>
</div>

在我的错误页面中,我想显示异常信息。 此外,如果存在404错误,我还有一个要求需要显示不同的消息。
3个回答

8
public class CustomExceptionFilter : HandleErrorAttribute {
    public override void OnException(ExceptionContext filterContext) {

        var controller = filterContext.Controller as Controller;
        controller.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
        controller.Response.TrySkipIisCustomErrors = true;
        filterContext.ExceptionHandled = true;

        var controllerName = (string)filterContext.RouteData.Values["controller"];
        var actionName = (string)filterContext.RouteData.Values["action"];
        var exception = filterContext.Exception;
        //need a model to pass exception data to error view
        var model = new HandleErrorInfo(exception, controllerName, actionName);

        var view = new ViewResult();
        view.ViewName = "Error";
        view.ViewData = new ViewDataDictionary();
        view.ViewData.Model = model;

        //copy any view data from original control over to error view
        //so they can be accessible.
        var viewData = controller.ViewData;
        if (viewData != null && viewData.Count > 0) {
            viewData.ToList().ForEach(view.ViewData.Add);
        }

        //Instead of this
        ////filterContext.Result = view;
        //Allow the error view to display on the same URL the error occurred
        view.ExecuteResult(filterContext);

        //should do any logging after view has already been rendered for improved performance.
        //_logger.Error("Uncaught exception", exception);

    }
}

Views/Shared/Error.cshtml

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}
<div class="row">
    <div class="col-sm-12">
        <h1>Error</h1>
        <div class="col-sm-12">
            <h2>An error occurred while processing your request.</h2>
        </div>
        <div>
            @{
                if (Model != null && Model.Exception != null) {
                    <h5>Here is some information you can pass on to the administrator</h5>
                    <h3>Path: ~/@string.Format("{0}/{1}", Model.ControllerName, Model.ActionName)</h3>
                    <h4>Error: @Model.Exception.GetType().Name</h4>
                    if (Request.IsLocal) {
                        <h4>Message: @Model.Exception.Message</h4>
                        <h5>@Model.Exception.StackTrace</h5>
                    }
                }
            }
        </div>
    </div>
</div>

Web.Config

<customErrors mode="Off"/>

它抛出了什么错误?确保在项目“Views/Shared/Error.cshtml”中具有错误视图的位置。 - Nkosi
好的,那个错误看起来可能是在错误视图中出现了问题。查看这篇文章,看看能否解决它。https://dev59.com/1o3da4cB1Zd3GeqPy1xK#31609192 - Nkosi
这表明该属性应该存在。https://msdn.microsoft.com/zh-cn/library/system.web.mvc.handleerrorinfo(v=vs.118).aspx - Nkosi
哦,我明白了,你显然写成了“@model System.Web.Mvc.HandleErrorAttribute”,应该是“@model System.Web.Mvc.HandleErrorInfo”……让我试一下,如果有问题会告诉你。 - Gaurav123
哎呀,我的错。是的,那是个打字错误。我把它从你的原始问题中复制过来了。 - Nkosi
显示剩余15条评论

1

您可以尝试像这样发送

filterContext.HttpContext.Items["Exception"] = Exception.Message;

0

我知道这是一个旧帖子,但我只想分享最简单的方法。只需将此粘贴到您的Web.config中即可。

 <system.web>
 <customErrors mode="On" defaultRedirect="~/home">
      <error statusCode="404" redirect="~/Error.html"/>
      <error statusCode="403" redirect="~/Error.html"/>
  </customErrors>
 <system.web>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接