自定义过滤器属性注入依赖性

自定义过滤器属性注入依赖性

本文介绍了自定义过滤器属性注入依赖性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET Web API,需要获得授权,因此我创建了自定义授权属性

I'musing ASP.NET Web API and I need to have authorization so I've created custom authorization attribute

public class CustomAuthorizationAttribute : AuthorizeAttribute

为了在构造函数中注入依赖项,我有以下内容:

In order to inject dependency inside constructor I have following :

        public CustomAuthorizationAttribute(IAccountBL accountBl)
    {
        _accountBL = accountBl;
    }

IAccountBL 中,我有一种与数据库交互的方法,用于检查用户是否有权发出请求.在成员API控制器内部,我已经注册了该属性

In IAccountBL I have method which interacts with database checking if user is authorized to make request.Inside Member API controller I've register that attribute

    [CustomAuthorization]
public class MemberController : ApiController

但是我收到以下错误

如果我像

[CustomAuthorization(IAccountBL)]

谢谢

推荐答案

如果有人发现了类似的问题,这就是我设法解决的问题.

If anyone finds similar issue here's how I manage to solve it.

我的自定义过滤器继承了 IAutofacAuthorizationFilter .除了这一点,您还可以继承 IAutofacExceptionFilter IAutofacActionFilter .在我的DI容器中,我已经为要使用的每个控制器注册了此过滤器

My custom filter inherits IAutofacAuthorizationFilter. Besides this one you can also inherit IAutofacExceptionFilter and IAutofacActionFilter.And inside my DI container I've register this filter for each controller I want to use like this

        builder.Register(c => new CustomAuthorizationAttribute(c.Resolve<IAccountBL>()))
               .AsWebApiAuthorizationFilterFor<MemberController>()
               .InstancePerApiRequest();

这篇关于自定义过滤器属性注入依赖性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:40