如何在共享视图Error.cshtml中显示异常消息?

问题描述 投票:4回答:1

如果我从一个新的MVC 5项目开始,在web.config设置中,customErrors mode =“on”允许共享视图'Error.cshtml'在我强制(引发)异常时显示,但它只显示以下文本.. 。

错误。

处理您的请求时发生错误。

如何将信息传递到此视图以显示更多相关信息,例如发生了什么错误?如果我使用Global.asax方法,我可以使用此视图吗?

protected void Application_Error()

?

c# asp.net-mvc razor error-handling asp.net-mvc-5
1个回答
9
投票

覆盖过滤器:

// In your App_Start folder
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ErrorFilter());
        filters.Add(new HandleErrorAttribute());
        filters.Add(new SessionFilter());
    }
}

// In your filters folder (create this)
public class ErrorFilter : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
    {
        System.Exception exception = filterContext.Exception;
        string controller = filterContext.RouteData.Values["controller"].ToString();;
        string action = filterContext.RouteData.Values["action"].ToString();

        if (filterContext.ExceptionHandled)
        {
            return;
        }
        else
        {
            // Determine the return type of the action
            string actionName = filterContext.RouteData.Values["action"].ToString();
            Type controllerType = filterContext.Controller.GetType();
            var method = controllerType.GetMethod(actionName);
            var returnType = method.ReturnType;

            // If the action that generated the exception returns JSON
            if (returnType.Equals(typeof(JsonResult)))
            {
                filterContext.Result = new JsonResult()
                {
                    Data = "DATA not returned"
                };
            }

            // If the action that generated the exception returns a view
            if (returnType.Equals(typeof(ActionResult))
                || (returnType).IsSubclassOf(typeof(ActionResult)))
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "Error"
                };
            }
        }

        // Make sure that we mark the exception as handled
        filterContext.ExceptionHandled = true;
    }
}

在“错误”视图的顶部声明模型:

@model System.Web.Mvc.HandleErrorInfo

然后在页面上使用如下:

@if (Model != null)
{
    <div>
        @Model.Exception.Message
        <br />
        @Model.ControllerName
    </div>
}

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.