Setup filter attribute for dependency injection to accept params in constructor

后端 未结 1 1694
醉梦人生
醉梦人生 2021-01-02 19:18

I\'m following a ninject filter attribute setup on this page.

For them, they have:

.WithConstructorArgumentFromControllerAttribute

        
相关标签:
1条回答
  • 2021-01-02 19:34

    You need to make roles into a property in your attribute.

    Attribute:

    public class AuthAttribute : FilterAttribute 
    { 
      public string[] Roles { get; set; }
    
      public AuthAttribute(params string[] roles)
      {
          this.Roles = roles;
      }
    }
    

    Filter:

    public class AuthFilter : IAuthorizationFilter
    {
    
      private readonly IUserService userService;
      private readonly string[] roles;
    
      public AuthFilter(IUserService userService, string[] roles)
      {
        this.userService = userService;
        this.roles = roles;
      }
    
      public void OnAuthorization(AuthorizationContext filterContext)
      {
        //do stuff
      }
    }
    

    Controller

       [AuthAttribute("a", "b")]
       public class YourController : Controller 
       {
    
       }
    

    Binding:

    kernel.BindFilter<AuthFilter>(FilterScope.Controller, 0)
                .WhenControllerHas<AuthAttribute>()
                .WithConstructorArgumentFromControllerAttribute<AuthAttribute>("roles", attribute => attribute.Roles);
    
    0 讨论(0)
提交回复
热议问题