2

I need to add redirects based on hostname, reading the map of source-path/destination-path from the database.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMemoryCache memoryCache, ILoggerFactory loggerFactory, myDbContext db)
{
    app.UseRewriter(new RewriteOptions()
       .AddRedirect("(.*)/$", "$1")
       .Add(ctx => {

            var req = ctx.HttpContext.Request;
            var hostName = req.Host;

            /*
            ** here I am willing to use db to do something like...
            */

            var redirects = db.redirect
                .Where(r=> r.host == hostName ).ToList();

            /*
            ** so that I can do something like this:
            */

            var newUrl = DetermineNewUrl(req,redirects);
            var response = ctx.HttpContext.Response;
            response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Location] = newUrl;
            response.StatusCode = 301;
            ctx.Result = RuleResult.EndResponse;
    }));
}

But it doesn't work, because db is supposedly disposed:

enter image description here

DbContext is added in ConfigureServices like this (scoped):

  var connection = Configuration.GetConnectionString("DefaultConnection");
  services.AddDbContext<gommeautoContext>(options => options.UseSqlServer(connection, sqlServerOptionsAction: sqlOptions =>
  {
    sqlOptions.EnableRetryOnFailure(maxRetryCount: 5,
    maxRetryDelay: TimeSpan.FromSeconds(5),
    errorNumbersToAdd: null);
  }));

And my last attempt to make it work was using the following code:

  using (var serviceScope = app.ApplicationServices.CreateScope())
  {
    var services = serviceScope.ServiceProvider;
    var _db = services.GetService<gommeautoContext>();
    var redirects = db.redirect
        .Where(r=> r.host == hostName ).ToList();
  }

But didn't help.

I assume it's not that simple to access dbContext inside UseRewriter.Add(, and I can't figure out how to do it...

Anyone does?

Max Favilli
  • 6,161
  • 3
  • 42
  • 62

1 Answers1

1

This approach was actually correct:

using (var serviceScope = app.ApplicationServices.CreateScope())
{
  var services = serviceScope.ServiceProvider;
  var _db = services.GetService<gommeautoContext>();

  ...

}

But I was misleaded by another issue, as pointed out here https://stackoverflow.com/a/43876571/395773 I had an earlier awaited call in my code returning void, implicitly disposing the context.

Max Favilli
  • 6,161
  • 3
  • 42
  • 62