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:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
private readonly ILoggerFactory _loggerFactory;
private readonly IHttpContextAccessor _contextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, ILoggerFactory loggerFactory, IHttpContextAccessor contextAccessor)
: base(options)
{
_loggerFactory = loggerFactory;
_contextAccessor = contextAccessor;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// use _contextAccessor.HttpContext here
...
}
And do not forget to register IHttpContextAccessor
to DI in ConfigureServices as "The IHttpContextAccessor service is not registered by default"
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
...
}