c# - 在使用 app.UseRewriter().Add() 添加重定向时访问 Startup.Configure 中的 dbcontext

标签 c# asp.net-core dependency-injection url-rewriting entity-framework-core

我需要添加基于主机名的重定向,从数据库中读取源路径/目标路径的映射。

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;
    }));
}

但它不起作用,因为据称 db 已被处置:

enter image description here

DbContext 是这样添加到 ConfigureServices 中的(作用域):

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

我最后的尝试是使用以下代码:

  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();
  }

但没有帮助。

我认为在 UseRewriter.Add( 中访问 dbContext 并不是那么简单,我不知道该怎么做...

有人做吗?

最佳答案

这个方法实际上是正确的:

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

  ...

}

但我被另一个问题误导了,正如这里指出的那样https://stackoverflow.com/a/43876571/395773我的代码中有一个较早的等待调用返回 void,隐式处理上下文。

关于c# - 在使用 app.UseRewriter().Add() 添加重定向时访问 Startup.Configure 中的 dbcontext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56136580/

相关文章:

java - Struts 2 bean配置默认作用域

asp.net-core - 在 DI 实例上使用 AutoMapper 8 ProjectTo

c# - 如何创建按月份排序的图表?

c# - 使用本地化的 Razor 页面作为电子邮件模板

c# - 建模 "I' m a * 但我也是一个 **”

c# - 传入 XML 大小写敏感问题

azure - 在 Azure AD B2C 中取消新用户注册重定向到站点主页,产生 "AuthorizationFailed"错误

java - Mockito - 什么规则管理类似 Collection 类的模拟注入(inject)?

c# - 如何使用 LINQ 从两个列表中有效地选择某些项目

c# - 来自特定程序集的 Unity DI 自动注册