I'm authenticating HTTP requests in middleware by querying data in the database, and to do so I need to configure the ApplicationDbContext with the data in HTTP request. How can I reach HTTP request from ApplicationDbContext.OnConfiguring ? (ASP .NET core / Entity framework core)
Middleware
public class TeamAuthentication
{
public async Task Invoke(HttpContext context, ApplicationDbContext db)
{
My.CheckToken(db);
// ...
DbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
private ILoggerFactory loggerFactory;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, ILoggerFactory _loggerFactory)
: base(options)
{
loggerFactory = _loggerFactory;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// how to reach HttpContext here ?
// ...
As you have already found, EF supports using DbContext with a dependency injection container. Inject
IHttpContextAccessor
in your dependencies and use it to obtain the current HttpContext:And do not forget to register
IHttpContextAccessor
to DI in ConfigureServices as "The IHttpContextAccessor service is not registered by default"