我正在尝试创建自定义authorize属性,但在使用默认依赖注入框架的asp.net vnext中,我不知道如何获取注入的对象.我需要在默认的ctor中获取注入的对象.
public class CustomAttribute { private IDb _db; public CustomAttribute() { _db = null; // get injected object } public CustomAttribute(IDb db) { _db = db; } // apply all authentication logic }
解决方法
您可以将
ServiceFilterAttribute用于此目的.服务过滤器属性允许DI系统负责实例化和维护过滤器CustomAuthorizeFilter及其任何所需服务的生命周期.
例:
// register with DI services.AddScoped<ApplicationDbContext>(); services.AddTransient<CustomAuthorizeFilter>(); //------------------ public class CustomAuthorizeFilter : IAsyncAuthorizationFilter { private readonly ApplicationDbContext _db; public CustomAuthorizeFilter(ApplicationDbContext db) { _db = db; } public Task OnAuthorizationAsync(AuthorizationContext context) { //do something here } } //------------------ [ServiceFilter(typeof(CustomAuthorizeFilter))] public class AdminController : Controller { // do something here }