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)
public class AuthorizeViewFilterProvider : System.Web.Http.Filters.IFilterProvider
{
private readonly Func<AuthorizeViewFilter> _authorizeViewFilterFactory;
public AuthorizeViewFilterProvider(Func<AuthorizeViewFilter> authorizeViewFilterFactory)
{
this._authorizeViewFilterFactory = authorizeViewFilterFactory;
}
public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
{
if(!actionDescriptor.GetCustomAttributes<AuthorizeViewAttribute>().Any())
return Enumerable.Empty<FilterInfo>();
return new[]
{
new FilterInfo(this._authorizeViewFilterFactory(), FilterScope.Action)
};
}
}
then create a webapi filter
public class AuthorizeViewFilter : System.Web.Http.Filters.IAuthorizationFilter
{
private readonly IAccessRightsService _iAccessRightService;
public AuthorizeViewFilter(IAccessRightsService iAccessRightService)
{
_iAccessRightService = iAccessRightService;
}
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(
HttpActionContext actionContext,
CancellationToken cancellationToken,
Func<Task<HttpResponseMessage>> continuation)
{
RoleFeature roleFeature = _iAccessRightService.GetRoleFeatures();
if (roleFeature.IsView)
{
return continuation();
}
else
return Task.FromResult(actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Access denied"));
}
}
then, bind the FilterProvider in your binding setup :
this.Bind<System.Web.Http.Filters.IFilterProvider>().To<AuthorizeViewFilterProvider>();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…