2011-05-05 4 views
7

사용자 지정 ASP.MVC 3 Action Filter를 구축 할 때 테스트에 실패하면 사용자를 다른 작업으로 리디렉션해야합니까? 사용자가 누락 된 환경 설정을 입력 한 후에 원본 페이지로 다시 리디렉션 할 수 있도록 원래 액션을 전달하고 싶습니다. 컨트롤러에서ASP.MVC 3 작업 필터에서 다른 컨트롤러 작업으로 사용자를 리디렉션하려면 어떻게합니까?

:

[FooRequired] 
public ActionResult Index() 
{ 
    // do something that requires foo 
} 

사용자 정의 필터 클래스 : 나는 간단한 ASP.MVC 3 필터 예제를 찾고 있어요

// 1. Do I need to inherit ActionFilterAttribute or implement IActionFilter? 
public class FooRequired : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if (TestForFoo() == false) 
     { 
      // 2. How do I get the current called action? 

      // 3. How do I redirect to a different action, 
      // and pass along current action so that I can 
      // redirect back here afterwards? 
     } 

     // 4. Do I need to call this? (I saw this part in an example) 
     base.OnActionExecuting(filterContext);    
    } 
} 

. 지금까지 내 검색을 통해 Ruby on Rails 예제 또는 ASP.MVC 필터 예제가 필요한 것보다 훨씬 복잡해졌습니다. 이전에 질문을 받았다면 사과드립니다.

+0

가능한 복제본 [ASP.NET MVC 3 리디렉션 액션 필터 속성] (http://stackoverflow.com/questions/5453338/asp-net-mvc-3-redirect-from-action-filter-attribute) – Talljoe

+1

그건 내 질문의 일부에 대한 해답이다. 내가 물어보기 전에 StackOverflow를 검색해 보았습니다. 기존 액션을 전달하는 방법이 궁금합니다. –

+0

@ Talljoe 및 개조 : 더 많은 가능한 중복 [asp.net mvc 작업 필터에서 지정된 컨트롤러 및 작업 리디렉션] (http://stackoverflow.com/questions/1490401/redirecting-to-specified-controller-and- action-in-asp-net-mvc-action-filter) –

답변

6

설정할 수있는 filterContext.ResultRedirectToRouteResult A와 : 당신이 경로를 차단하려는 경우를

public class PrelaunchModeAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     //If we're not actively directing traffic to the site... 
     if (ConfigurationManager.AppSettings["PrelaunchMode"].Equals("true")) 
     { 
      var routeDictionary = new RouteValueDictionary {{"action", "Index"}, {"controller", "ComingSoon"}}; 

      filterContext.Result = new RedirectToRouteResult(routeDictionary); 
     } 
    } 
} 

:

filterContext.Result = new RedirectToRouteResult(...); 
+1

이 작업은 현재 진행중인 경로를 따라가는 방법을 알아 내려고했기 때문에 어떤 작업이 중단되었는지 알 수 있습니다. –

+0

이것이 누락 된 성분이라고 생각합니다 : http://www.squaredroot.com/2008/04/01/redirecttoaction-with-parameter/ –

7

여기에 내 자신의 리디렉션 필터 중 하나를 사용하여 작은 코드 샘플입니다 ActionExecutingContext.RouteData member에서 가져올 수 있습니다.

var currentRoute = filterContext.RouteData.Route; 

이 기타 ... 그 질문에 답 않는다 : 그으로 RouteData 회원으로

, 당신은 원래의 경로를 얻을 수 있나요?

+0

어떻게 filterContext.RouteData.Route를 사용 했습니까? 나는 새로운 RedirectToRouteResult (filterContext.RouteData.Route)를 시도했다. – stormwild

관련 문제