10

다음과 같은 필터 특성을 가지고 있으며 문자열 배열을 [MyAttribute("string1", "string2")]과 같은 특성에 전달할 수 있습니다.asp.net의 조치 필터에 매개 변수를 추가하려면 어떻게합니까?

public class MyAttribute : TypeFilterAttribute 
{ 
    private readonly string[] _ids; 

    public MyAttribute(params string[] ids) : base(typeof(MyAttributeImpl)) 
    { 
     _ids = ids; 
    } 

    private class MyAttributeImpl : IActionFilter 
    { 
     private readonly ILogger _logger; 

     public MyAttributeImpl(ILoggerFactory loggerFactory) 
     { 
      _logger = loggerFactory.CreateLogger<MyAttribute>(); 
     } 

     public void OnActionExecuting(ActionExecutingContext context) 
     { 
      // HOW DO I ACCESS THE IDs VARIABLE HERE ??? 
     } 

     public void OnActionExecuted(ActionExecutedContext context) 
     { 
     } 
    } 
} 

문자열 배열 _ids을 조치 필터의 구현에 전달하는 방법은 무엇입니까? 나는 정말로 명백한 무엇인가 놓치고있다!?

+0

- 때문에 'TypeFilterAttribute' - ASP.NET 코어를 사용하고 계십니까? –

+0

예, 저는 -이 문제가 발생합니까? –

+0

내가 필요로하는 것을 얻기 위해 예전의 ASP.NET에서 예제를 보았지만 핵심에서는 TypeFilterAttribute 클래스를 구현하고 매개 변수를 전달하는 모든 예제가 보이지 않는 것처럼 보입니다. –

답변

23

TypedFilterAttribute에는 구현의 생성자에 인수를 전달할 수있는 속성 (유형은 object[])이 있습니다. 그래서 귀하의 예제에 적용하면이 코드를 사용할 수 있습니다 :

public class MyAttribute : TypeFilterAttribute 
{   
    public MyAttribute(params string[] ids) : base(typeof(MyAttributeImpl)) 
    { 
     Arguments = new object[] { ids }; 
    } 

    private class MyAttributeImpl : IActionFilter 
    { 
     private readonly string[] _ids; 
     private readonly ILogger _logger; 

     public MyAttributeImpl(ILoggerFactory loggerFactory, string[] ids) 
     { 
      _ids = ids; 
      _logger = loggerFactory.CreateLogger<MyAttribute>(); 
     } 

     public void OnActionExecuting(ActionExecutingContext context) 
     { 
      // NOW YOU CAN ACCESS _ids 
      foreach (var id in _ids) 
      { 
      } 
     } 

     public void OnActionExecuted(ActionExecutedContext context) 
     { 
     } 
    } 
} 
+1

이것은 꿈처럼 보입니다! 나는 그것을 줄 것이다 ... 고마워! –