2017-04-05 2 views
2

오류를 포착하는 모든 방법으로이 코드를 MVC 웹 응용 프로그램의 BaseController에 추가했습니다.MVC OnException에서 예외가 처리되는 이유는 무엇입니까?

public class BaseController : Controller 
{ 
    protected override void OnException(ExceptionContext filterContext) 
    { 
     _logger.Error(filterContext.Exception, "Website error page displayed."); 

     TempData["ErrorMessage"] = "Unspecified error - please contact support"; 
     filterContext.RouteData.Values["controller"] = "Error"; 
     filterContext.Result = new ViewResult 
     { 
      ViewName = "Error", 
     }; 

     filterContext.ExceptionHandled = true; 
    } 
} 

그리고 나는이 보이는 전용 ErrorController이는 :

오류가 응용 프로그램의 일부를 처리하고 사용자가 오류 페이지로 리디렉션됩니다
public class ErrorController : BaseController 
{ 
    [AllowAnonymous] 
    public ActionResult Error() 
    { 
     string errorMessage = "There has been an error"; 
     if(TempData["ErrorMessage"] != null) 
     { 
      errorMessage = TempData["ErrorMessage"].ToString(); 
     } 

     Logger.Warn("Error error page displayed with message {0}", errorMessage); 
     ViewBag.ErrorMessage = errorMessage; 
     return View("Error"); 
    } 
} 

이 잘 작동합니다 :

if (!await UserManager.IsEmailConfirmedAsync(user.Id)) 
{ 
    TempData["ErrorMessage"] = "You must have a confirmed email to log on."; 
    return RedirectToAction("Error", "Error"); 
} 

그러나, 오류가 처리되지 않은이며, 오류가보기 예상 렌더링하는 다음 BaseControllerOnException를 통해 라우팅되지만 경우 t에 오류 조치 그는 컨트롤러에 결코 부딪치지 않는다. 오류 메시지는 기본값을 가정하고 동작의 중단 점이 트립되지 않습니다.

왜 이런가요? OnException에서 컨트롤러 작업을 올바르게 호출하려면 어떻게해야합니까?

+0

[this] (http://stackoverflow.com/questions/960280/asp-net-mvc-controller-onexception-not-being-called)를 확인 하시겠습니까? – Berkay

+0

@Berkay 그건 전혀 문제가되지 않습니다. OnException 확실히 호출됩니다. 그러나 오류 컨트롤러로 리디렉션 할 때 오류 동작이 호출되고 있지 않습니다. –

+0

결과 속성을 이름으로 지정된보기를 반환하는'ViewResult'의 인스턴스로 설정합니다. 'ViewName = "Error",'에 다른 뷰 이름을 넣어서 확인할 수 있습니다. 그것은 viewname을 찾을 수 없다는 것을 말해야합니다.'기본적으로해야 할 일은 컨트롤러 액션'ErrorController'의'Error'로 리다이렉트하는 것입니다. –

답변

1

filterContext.Result은 유형이 ActionResult이며 ViewResult 및 RedirectToRouteResult와 호환되는 반환 유형입니다.

어떻게 ViewResult 기능은 단지 응답 스트림에 지정된보기를 렌더링합니다.

다른 쪽 RedirectToActionRedirectToRouteResult을 반환하며 이는 ActionResult에서도 파생되었으며 주어진 경로 데이터를 기반으로 라우팅 엔진에서 결정한 URL에 대해 HTTP 리디렉션을 수행합니다.

그래서 귀하의 경우에 당신은 은 그래서 당신이 그것을이 RedirectToRouteResult을 반환하고 사용자가 지정한 경로로 리디렉션됩니다으로 RedirectToAction("Error", "Error");를 사용해야하는 이유가 필요합니다.

관련 문제