2012-03-23 6 views

답변

18

이 경우 filterContext.Result를 사용할 수 있습니다.

public override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    //Check your condition here 
    if (true) 
    { 
     //Create your result 
     filterContext.Result = new EmptyResult(); 
    } 
    else 
     base.OnActionExecuting(filterContext); 
} 
+0

조건이 true 일 때 왜 base.OnActionExecuting을 건너 뛰나요? 내 경우에는 결과를 설정하기 전에 실행해야합니다. – xr280xr

33

내 다운로드 샘플 및 MSDN 문서 Filtering in ASP.NET MVC을 참조하십시오.

Result 속성을 null이 아닌 값으로 설정하여 OnActionExecutingOnResultExecuting 메서드에서 필터 실행을 취소 할 수 있습니다.

보류 중일 경우 OnActionExecutedOnActionExecuting 필터가 호출되지 않고 취소 된 필터 또는 보류 중 필터에 대해 호출자가 OnActionExecuted 메서드를 호출하지 않습니다.

이전에 실행 한 필터에 대한 OnActionExecuted 필터가 실행됩니다. OnResultExecutingandOnResultExecuted 필터가 모두 실행됩니다.

샘플에서 다음 코드는 특정 조건이 OnActionExecuting에 충족 될 때 특정 ActionResult을 반환하는 방법을 보여줍니다

if (filterContext.RouteData.Values.ContainsValue("Cancel")) 
{ 
    filterContext.Result = new RedirectResult("~/Home/Index"); 
    Trace.WriteLine(" Redirecting from Simple filter to /Home/Index"); 
} 
+2

두 개 이상의 필터가 있고 필터의 순서가 중요한 경우 필터를 등록 할 때 "Order"매개 변수를 지정하여 실행 순서를 제어 할 수 있도록해야합니다. Rick이 결과에 대한 세부 정보에서 설명한대로 filterContext.Result 속성이 작동합니다. –

+0

좋은 지적 Nick - 내 섹션 참조 Filter Order - order 속성은 같은 클래스의 필터에만 적용됩니다. Auth는 항상 first, exception, last를 실행합니다. – RickAndMSFT

3

당신은 여기에 다음과 같은 코드를 사용할 수 있습니다.

public override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    ... 
    if (needToRedirect) //your condition here 
    { 
     ... 
     filterContext.Result = new RedirectToAction(string action, string controller) 
     return; 
    } 
    ... 
} 

RedirectToAction은 조건에 따라 특정 동작을 리디렉션합니다.

+0

RedirectToAction은 (적어도 MVC5에서는) 메소드이므로 new() 할 수 없습니다. – rumblefx0

관련 문제