8

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

For them, they have:

.WithConstructorArgumentFromControllerAttribute<LogAttribute>(
      "logLevel", attribute => attribute.LogLevel);

The second parameter is expecting a Func<LogAttribute, object> callback. Their actual param list is setup as follows:

Log(LogLevel = Level.Debug)

But my filter attribute is setup as follows:

public class AuthAttribute : FilterAttribute { }

public class AuthFilter : IAuthorizationFilter
{

    private readonly IUserService userService;
    private string[] roles;

    //Stuck on the constructor also. How do I accept params?
    public AuthFilter(IUserService userService, params string[] roles)
    {
        this.userService = userService;
        this.roles = roles;
    }
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        throw new NotImplementedException();
    }
}

Somehow this is wrong. Because I want my filter to look like:

[Auth("Admin", "Contrib")]

My bindings:

 kernel.BindFilter<AuthFilter>(FilterScope.Controller, 0)
            .WhenControllerHas<AuthAttribute>()
            .WithConstructorArgumentFromControllerAttribute<AuthAttribute>("roles", /*Stuck here*/)

1 Answer 1

18

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);
Sign up to request clarification or add additional context in comments.

10 Comments

So I remove this from the constructor?
And how do I access it in the OnAuthorization method?
Thanks this works. How do I setup the binding for both controller and action? When I have another binding for actions, it says multiple bindings found.
@Lol coder...hmm, not sure what the issue could be, the ninject documentation has good examples on how to setup both. Maybe try posting a different question, someone may be able to help more.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.