2011-12-23 1 views
0
public abstract class MyControllerBase : Controller 
{ 
    protected override void OnActionExecuting(ActionExecutingContext context) 
    { 
     // do some magic 
    } 
} 

모든 컨트롤러는 MyControllerBase에서 상속됩니다. 문제는 필터가 코드 경로에 영향을 미치는 몇 가지 인증/논리 플래그를 설정하기 때문에 특정 메소드를 테스트 할 수 없다는 것입니다.MVC 사용자 지정 필터, 단위 테스트 용으로 수동으로 ASP.NET 파이프 라인 이벤트 호출

OnActionExecuting을 수동으로 트리거 할 수있는 방법이 있습니까? 파이프 라인이 이러한 이벤트를 어떻게 유발합니까?

편집 : 덧글에 대한 응답으로이 디자인의 아이디어를 조금 더 보여줍니다. 나는 기본적으로 이런 일이 : 그래서 지금 현재 사용자의 정보를 얻을 수 있습니다 어디서나 View 또는 Controller

public abstract class MyControllerBase : Controller 
{ 
    protected override void OnActionExecuting(ActionExecutingContext context) 
    { 
     UserProperties = 
      _userService 
       .GetUserProperties(filterContext.HttpContext.User.Identity.Name); 

     ViewBag.UserProperties = UserProperties; 
    } 

    public UserProperties { get; private set; } 

    public bool CheckSomethingAboutUser() 
    { 
     return UserProperties != null 
      && UserProperties.IsAuthorisedToPerformThisAction; 
    } 

    // ... etc, other methods for querying UserProperties 
} 

를 이메일 무엇을, 그들이 가지고있는 권한 부여, 어떤 부서들은 등을 위해 일

예 :

public class PurchasingController : MyControllerBase 
{ 
    public ActionResult RaisePurchaseOrder(Item item) 
    { 
     // can use UserProperties from base class to determine correct action... 

     if (UserProperties.CanRaiseOrders) 

     if (UserProperties.Department == item.AllocatedDepartment) 
    } 
} 

그래서이 디자인은 정말 좋은 작동하지만, 당신이 테스트를 볼 수 내가 직접 설정 한 시험에서 UserProperties를 조작 할 수 없기 때문에 위의 작업은 어렵다. 난 당신이 MCV에서 그런 OnActionExecuting을 무시할 생각하고 있는지 모르겠어요

답변

2

는, 일반적으로 나는 그런 다음 ActionFilterAttribute

public class SomeMagicAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 

    } 
} 

만들 클래스 : 당신의 단위 테스트에서 다음

[SomeMagic] 
public abstract class MyControllerBase : Controller 
{ 

} 

당신 할 수있다

var magic = new SomeMagicAttribute(); 
var simulatedContext = new ActionExecutingContext(); 
magic.OnActionExecuting(simulatedContext); 
+0

여기에있는 문제는 'OnActionExecuting' 이벤트에서 som e 플래그를'ViewBag'에 그리고'MyControllerBase'에있는 public 속성들에 적용합니다. 이 값은 이제 모든 컨트롤러와 뷰에서 모든 곳에서 사용할 수 있습니다. 내 기억은 다소 모호하지만, 어떻게하면 커스텀'ActionFilterAttribute'를 사용하여 그것이 가능했는지 알 수 없기 때문에 디자인을 선택했다고 생각합니다. 아이디어가 있으십니까? – fearofawhackplanet

+0

'OnActionExecuting'의 마법을 게시 할 수 있습니까? 적어도 뷰백의 내용을 설정하기 위해서'filterContext.Controller.ViewBag.magic = 42; '를 쓸 수 있습니다. –

+0

디자인에 대한 아이디어를 보여주기 위해 질문을 업데이트했습니다. 'OnActionExecuting'은 영리한 일을하지 않으며, 전 세계적으로 이용 가능하게하고 싶은 일부 사용자 정보에 접근합니다. 내가 잘못하고 있다고 생각하면 귀하의 의견을 크게 환영합니다. – fearofawhackplanet