【问题标题】:Asp.Net Mvc Display exception in View from tempdataAsp.Net Mvc 在临时数据的视图中显示异常
【发布时间】:2014-04-08 03:39:09
【问题描述】:

我正在处理 Base 控制器中的错误。我需要在剃刀视图中显示存储在临时数据中的错误,异常类型。我该怎么做?

基本控制器代码

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>

【问题讨论】:

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


    【解决方案1】:

    尝试做通用异常属性处理,注册为全局过滤器。喜欢,

    常见异常处理属性:

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

    【讨论】:

      【解决方案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 对象。这可能是所需的行为,但您可以通过属性选择性地启用此功能。

      【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 它会抛出错误。当前上下文中不存在 TempData。
      猜你喜欢
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 2013-09-21
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 2014-10-06
      • 1970-01-01
      相关资源
      最近更新 更多