【问题标题】:How to pass error message to error view in MVC 5?如何将错误消息传递到 MVC 5 中的错误视图?
【发布时间】:2016-08-31 09:54:59
【问题描述】:

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

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 error 存在的情况下显示不同的消息。

【问题讨论】:

    标签: c# asp.net exception asp.net-mvc-5


    【解决方案1】:
    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"/>
    

    【讨论】:

    • ``view.ExecuteResult(filterContext)`` 正在抛出异常
    • 它抛出了什么错误?确保您在项目Views/Shared/Error.cshtml中的此位置有错误视图
    • System.Web.dll 中发生了“System.Web.HttpCompileException”类型的异常,但未在用户代码中处理
    • 好的,错误看起来可能是错误视图中的问题。检查这篇文章,看看你是否可以解决它。 stackoverflow.com/a/31609192/5233410
    • 谢谢...System.Web.Mvc.HandleErrorAttribute 不包含Exception 的定义,而是包含ExceptionType
    【解决方案2】:

    你可以试试这样发送

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-22
        • 2014-11-24
        • 1970-01-01
        • 2022-01-15
        相关资源
        最近更新 更多