2014-03-05 117 views
1

我正在處理基本控制器中的錯誤。我需要在剃鬚刀視圖中顯示存儲在tempdata,Exception類型中的錯誤。我怎樣才能做到這一點?Asp.Net Mvc從tempdata中查看異常

基本控制器代碼

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> 

回答

4

嘗試進行通用異常屬性處理並將其註冊爲全局過濾器。像,

常見的異常處理屬性:

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

和ERROR/_Error視圖

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

我會強烈建議不要表現出任何面向公衆的應用程序的任何詳細的異常信息,因爲這最終可能爲一個安全問題。但是,如果這是受控訪問內部網應用程序,或者如果你真的想顯示異常的詳細信息,創建一個DisplayTemplate並使用它,如下所示:

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

它拋出錯誤。 TempData在當前上下文中不存在。 – Kurkula

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對象。這可能是所需的行爲,但有了一個屬性,您可以選擇性啓用此功能。

+1

您也可以使用HandleErrorAttribute。看看這個帖子。 http://stackoverflow.com/questions/19025999/using-of-handleerrorattribute-in-asp-net-mvc-application – tulde23

+0

我怎樣才能得到異常類型? – Kurkula

+1

filterContext.Exception – tulde23