我需要添加基于主机名的重定向,从数据库中读取源路径/目标路径的映射。
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 已被处置:
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/