How To Add Database Context To Filter In Net Core 2 0


Hello everybody,

today I want to write a short description on how to add database context to IAuthorizationFilter.

Imagine that you have following filter:

public class HasApprovedFilter : AttributeIAuthorizationFilter
    private SomeDbContext _context;
    public HasApprovedFilter(SomeDbContext context)
        this._context = context;
    public void OnAuthorization(AuthorizationFilterContext context)
        var user = context.HttpContext.User;
        if (!user.Identity.IsAuthenticated)
        var userAdd = _context.;
        //var um = context.HttpContext.RequestServices.GetService();

As you can see, that filter requires in constructor SomeDbContext. How to add pass it to this filter?

Basically you'll need two steps:

1. At Startup class, in method ConfigureServices add following line:


right before line services.AddMvc();

2. At needed controller or Action of controller you can make like this:

public class HistoryController : Controller

such approach will allow you to have access to database at Filter level. 


ServiceFilter is entity which takes care about connecting your filter to dependency injection container. You can use it in order to pass not only DataBaseContext, but some other staff.

No Comments


Add a Comment


Comments are closed