2014-03-05 3 views
1

기본 컨트롤러에서 처리 오류가 발생했습니다. 나는 tempdata에 저장된 오류를 표시해야하며 예외 유형은 면도기보기에 표시해야합니다. 어떻게해야합니까? 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(); 
} 

면도기 코드보기

<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보기

@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 메서드를 재정의하면 모든 작업에서 temp 데이터에 Exception 개체가 배치됩니다. 원하는 동작 일 수도 있지만 속성을 사용하면이 기능을 선택적으로 활성화 할 수 있습니다.

+1

HandleErrorAttribute를 사용할 수도 있습니다. 이 게시물을보십시오. http://stackoverflow.com/questions/19025999/using-of-handleerrorattribute-in-asp-net-mvc-application – tulde23

+0

예외 유형을 어떻게 얻을 수 있습니까? – Kurkula

+1

filterContext.Exception – tulde23

관련 문제