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

时间:2015-07-15 21:14:55

标签: c# asp.net-mvc razor error-handling asp.net-mvc-5

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

  

错误。

     

处理您的请求时出错。

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

protected void Application_Error()

1 个答案:

答案 0 :(得分:9)

覆盖过滤器:

$repository = $em->getRepository('Gedmo\\Translatable\\Entity\\Translation');

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

// 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

希望这有帮助。