Get embedded object in ASP.NET vNext filter

I am trying to create my custom authorize attribute, but in asp.net vnext using the default dependency injection infrastructure, I don’t understand how to get the entered object. I need to get the entered object by default ctor.

public class CustomAttribute { private IDb _db; public CustomAttribute() { _db = null; // get injected object } public CustomAttribute(IDb db) { _db = db; } // apply all authentication logic } 
+6
source share
1 answer

You can use ServiceFilterAttribute for this purpose. The service filter attribute allows the DI system to take care of instantiating and maintain the lifetime of the CustomAuthorizeFilter filter and any necessary services.

Example:

 // 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 } 
+9
source

Source: https://habr.com/ru/post/978217/


All Articles