C# 在Startup.Configure中访问dbcontext,同时使用app.UseRewriter().Add()添加重定向
我需要根据主机名添加重定向,从数据库读取源路径/目标路径的映射C# 在Startup.Configure中访问dbcontext,同时使用app.UseRewriter().Add()添加重定向,c#,asp.net-core,dependency-injection,url-rewriting,entity-framework-core,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("(.*)/$", "
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(选项=>options.UseSqlServer(连接,SQLServerOptions操作: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();
}
使用(var serviceScope=app.ApplicationServices.CreateScope())
{
var services=serviceScope.ServiceProvider;
var_db=services.GetService();
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>();
...
}
使用(var serviceScope=app.ApplicationServices.CreateScope())
{
var services=serviceScope.ServiceProvider;
var_db=services.GetService();
...
}
但我被另一个问题误导了,正如这里所指出的,我的代码中有一个等待已久的调用返回void,隐式地处理上下文。我猜是范围化的,编辑了问题以添加如何在ConfigureServices中添加的代码片段,我的最后一次尝试是:使用(var serviceScope=app.ApplicationServices.CreateScope()){var services=serviceScope.ServiceProvider;var_db=services.GetService();}但不起作用。将其添加到您的帖子中,会使事情变得更清楚。现在检查一下。希望没问题。看起来不错,看看这篇帖子()被接受的答案和彼得的答案可能会对你有所帮助。+1来自我。@RyanWilson非常感谢,彼得的答案解决了这个问题!
using (var serviceScope = app.ApplicationServices.CreateScope())
{
var services = serviceScope.ServiceProvider;
var _db = services.GetService<gommeautoContext>();
...
}