How do I show Exception message in shared view Error.cshtml?

风格不统一 提交于 2019-12-04 07:25:35
Denys

Override the filter:

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

Declare the model at the top of the 'error' view:

@model System.Web.Mvc.HandleErrorInfo

Then use on the page like so:

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

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!