WebApi Custom Filter with injected interface in constructor does not get called

后端 未结 1 1277
花落未央
花落未央 2020-12-20 08:25

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 li

相关标签:
1条回答
  • 2020-12-20 08:52

    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>();
    
    0 讨论(0)
提交回复
热议问题