How to get HTTP context from ApplicationDbContext.OnConfiguring?

asp.net-core entity-framework-core httpcontext

Question

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 ?
        // ...
1
1
1/10/2017 9:45:13 AM

Accepted Answer

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>();
    ...
}
2
1/10/2017 10:06:55 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow