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?
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:
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;
}
Add VerifyProfile
to the DI container:
services.AddScoped<VerifyProfile>();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With