2015-02-02 11 views
0

WebAPI에서 컨트롤러의 일부 동작에 대한 테스트를하고 있습니다. 나는 그것이 모든 테스트에 대한 설정으로 하나의 보편적 인 범위가되도록 Autofac을 구성하려고합니다.모든 ApiController에 대한 정품 인증 동작을 등록하십시오.

Autofac에서 ApiController을 요청할 때마다 사용자 인증을 테스트 할 수 있도록 ClaimsIdentity를 만들고 싶습니다.

newBuilder.RegisterType<ApiController>().OnActivated(c => 
{ 
    var controller = c.Instance; 
    controller.Request = Message; 
    var identity = new ClaimsIdentity(); 
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, UserId)); 
    controller.User = new ClaimsPrincipal(identity); 
}); 

newBuilder.Update(container); 

그러나이 작동하지 않습니다 : 나는 그것을 수행하려고 할 방법

이입니다. ApiController을 실제 컨트롤러로 바꾸면 제대로 작동합니다.

내 컨트롤러는 다음과 같이 등록 : 나는 실제로 내가 설명처럼 뭔가를 관리했습니다

builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); 

답변

0

, 내가 (하지만 작동) 솔루션과 완벽하게 만족하지 않다 있지만.

// Get any controller from the namespace where all the controllers are 
var asm = Assembly.GetAssembly(typeof(UserController)); 

foreach (var type in asm.GetTypes()) 
{ 
    if (type.Namespace == "Namespace.With.Controllers" && type.IsSubclassOf(typeof(ApiController))) 
    { 
     newBuilder.RegisterType(type).OnActivated(c => 
     { 
      var controller = (ApiController)c.Instance; 
      controller.Request = Message; 
      var identity = new ClaimsIdentity(); 
      identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, UserId)); 
      controller.User = new ClaimsPrincipal(identity); 
     }); 
    } 
} 
관련 문제