从tempdata查看Asp.Net Mvc异常

时间:2014-03-05 20:34:19

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

我在Base控制器中处理错误。我需要在剃刀视图中显示存储在tempdata,Exception类型中的错误。我怎么能这样做?

基本控制器代码

protected override void OnException(ExceptionContext filterContext)
{
    // if (filterContext.ExceptionHandled)
    //   return;

    //Let the request know what went wrong
    filterContext.Controller.TempData["Exception"] = filterContext.Exception.Message;

    //redirect to error handler
    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
            new { controller = "Error", action = "Index" }));

    // Stop any other exception handlers from running
    filterContext.ExceptionHandled = true;

    // CLear out anything already in the response
    filterContext.HttpContext.Response.Clear();
}

Razor查看代码

<div>
    This is the error Description
    @Html.Raw(Html.Encode(TempData["Exception"]))
</div>

3 个答案:

答案 0 :(得分:4)

尝试进行常见的异常属性处理并将其注册为全局过滤器。像,

Common Exception Handling属性:

    /// <summary>
    /// This action filter will handle the errors which has http response code 500. 
    /// As Ajax is not handling this error.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public sealed class HandleErrorAttribute : FilterAttribute, IExceptionFilter
    {
        private Type exceptionType = typeof(Exception);

        private const string DefaultView = "Error";

        private const string DefaultAjaxView = "_Error";

        public Type ExceptionType
        {
            get
            {
                return this.exceptionType;
            }

            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }

                this.exceptionType = value;
            }
        }

        public string View { get; set; }

        public string Master { get; set; }

        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled))
            {
                Exception innerException = filterContext.Exception;

                // adding the internal server error (500 status http code)
                if ((new HttpException(null, innerException).GetHttpCode() == 500) && this.ExceptionType.IsInstanceOfType(innerException))
                {
                    var controllerName = (string)filterContext.RouteData.Values["controller"];
                    var actionName = (string)filterContext.RouteData.Values["action"];
                    var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                    // checking for Ajax request
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        var result = new PartialViewResult
                        {
                            ViewName = string.IsNullOrEmpty(this.View) ? DefaultAjaxView : this.View,
                            ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                            TempData = filterContext.Controller.TempData
                        };
                        filterContext.Result = result;
                    }
                    else
                    {
                        var result = this.CreateActionResult(filterContext, model);
                        filterContext.Result = result;
                    }

                    filterContext.ExceptionHandled = true;
                }
            }
        }

        private ActionResult CreateActionResult(ExceptionContext filterContext, HandleErrorInfo model)
        {
            var result = new ViewResult
            {
                ViewName = string.IsNullOrEmpty(this.View) ? DefaultView : this.View,
                MasterName = this.Master,
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData,
            };

            result.TempData["Exception"] = filterContext.Exception;

            return result;
        }
    }

和错误/ _错误视图

@model HandleErrorInfo
<div>
    This is the error Description
    @TempData["Exception"]
 </div>

答案 1 :(得分:2)

我强烈建议不要在任何面向公众的应用程序中显示任何详细的异常信息,因为这可能最终成为安全问题。但是,如果这是具有受控访问权限的Intranet应用程序,或者您真的想要显示异常详细信息,请创建一个DisplayTemplate并按如下方式使用它:

<div>
Exception Details
@Html.Display(TempData["Exception"])
</div>

答案 2 :(得分:2)

我同意您不应该在视图中公开异常,但如果您确实需要,请尝试使用自定义属性。

 public class CustomExceptionAttribute : System.Web.Mvc.HandleErrorAttribute
    {
        public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                filterContext.Controller.TempData.Add("Exception", filterContext.Exception);
                filterContext.ExceptionHandled = true;
            }
        }
    }

    public class MyController : System.Web.Mvc.Controller
    {
        [CustomException]
        public ActionResult Test()
        {
            throw new InvalidOperationException();
        }
    }

如果覆盖基本控制器中的OnException方法,则每个操作都将获得放置在临时数据中的Exception对象。这可能是所需的行为,但有了属性,您可以有选择地启用此功能。