My problem statement is same as this question i.e., use an injected service in attribute/filter. I have tried the solution given by B Z and following is my code along the lines of solution given.
//marker attribute
public class AuthorizeViewAttribute : Attribute { }
//filter
public class AuthorizeViewFilter : IAuthorizationFilter
{
private readonly IAccessRightsService _iAccessRightService;
public AuthorizeViewFilter(IAccessRightsService iAccessRightService)
{
_iAccessRightService = iAccessRightService;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
RoleFeature roleFeature = _iAccessRightService.GetRoleFeatures();
if (roleFeature.IsView)
{
//redirect to controller
}
}
}
Following is the ninject binding I use:
this.BindFilter<AuthorizeViewFilter>(System.Web.Mvc.FilterScope.Controller, 0)
.WhenControllerHas<AuthorizeViewAttribute>();
I do not need any parameter in attribute, so I figured I do not need to use WithConstructorArgument as mentioned in this answer
But my filter never gets called. I put a default constructor in AuthorizeViewAttribute , debugged and found that the control jumps to default constructor in AuthorizeViewAttribute and continues with the controller method.
I cannot find any solution to this. Any suggestions?
Short story : You seem to be trying to use MVC filter and MVC binding on a webapi controller. That's why it does not work.
Long story : first create a webapi filter provider ( note, you will need Ninject.Extensions.Factories package to have
Func<AuthorizeViewFilter>
resolved by Ninject)then create a webapi filter
then, bind the FilterProvider in your binding setup :