Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use DbContext in ActionFilter Middleware

I want to use a DbContext in my ActionFilter Middleware. Is it possible?

public class VerifyProfile : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        using (var context = new SamuraiDbContext())
        {
            var user = filterContext.HttpContext.User.Identity.Name;
            if (context.Profiles.SingleOrDefaultAsync(p => p.IdentityName == user).Result == null)
            {
                filterContext.Result = new RedirectResult("~/admin/setup");
            }
        }
    }
}

But this code using (var context = new SamuraiDbContext()) requires to pass options. Should I again pass DbContextOptionsBuilder() here or is there any other way?

I want to have [VerifyProfile] attribute in my controllers method. Is it possible or not?

like image 702
user3127109 Avatar asked Apr 26 '18 10:04

user3127109


1 Answers

Instead of trying to create a new instance of SamuraiDbContext yourself, use Dependency Injection in your Filter. To achieve this, you need to do three things:

  1. Add a constructor to VerifyProfile with a parameter of type SamuraiDbContext and store it as a field:

    private readonly SamuraiDbContext dbContext;
    
    public VerifyProfile(SamuraiDbContext dbContext)
    {
        this.dbContext = dbContext;
    }
    
  2. Add VerifyProfile to the DI container:

    services.AddScoped<VerifyProfile>();
    
  3. Use ServiceFilter to take care of connecting your filter to the DI container:

    [ServiceFilter(typeof(VerifyProfile))]
    public IActionResult YourAction()
        ...
    

You can apply the ServiceFilter attribute at the action level, as shown, or at the controller level. You can also apply it globally. To do that, replace step 3 above with the following:

services.AddMvc(options =>
{
    options.Filters.Add<VerifyProfile>();
});

As an additional resource, this blog post has a good write up of some of the other options.

like image 173
Kirk Larkin Avatar answered Sep 20 '22 21:09

Kirk Larkin