c# - 在 ASP.NET 中间件中更改 DbContext
问题描述
public class RequestCultureMiddleware
{
private readonly RequestDelegate _next;
public RequestCultureMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var cultureQuery = context.Request.Query["culture"];
if (!string.IsNullOrWhiteSpace(cultureQuery))
{
var culture = new CultureInfo(cultureQuery);
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
}
// Call the next delegate/middleware in the pipeline
await _next(context);
}
在此示例中,实现了自定义中间件。我想根据我在这个中间件中所做的事情来更改 DbContext。我可以添加一个将被注入的 DbContext 参数,然后用它做我需要做的事情:
public async Task InvokeAsync(HttpContext context, MyDbContext context)
{
context.Database.GetDbConnection().ConnectionString = "..."; // +
var cultureQuery = context.Request.Query["culture"];
if (!string.IsNullOrWhiteSpace(cultureQuery))
{
var culture = new CultureInfo(cultureQuery);
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
}
// Call the next delegate/middleware in the pipeline
await _next(context);
}
但是,我将如何传播新的 DbContext?
解决方案
您必须像这样注册您DbContext
的ConfigureServices
:
services.AddScoped<MyDbContext>(sp=> {
var httpContextAccessor = sp.GetRequiredService<IHttpContextAccessor>();
var httpContext = httpContextAccessor.HttpContext;
var request = httpContext.Request;
// form your connection string here based on data
// from the request and pass it down to DbContext constructor
var connString = "...";
return new MyDbContext(connString);
});
您还必须添加services.AddHttpContextAccessor()
它才能正常工作。
推荐阅读
- node.js - 在 NodeJS 中列出 Azure 中的所有资源
- c++ - r 值成员的用例
- html - 如何移动我放置圆形裁剪的部分图像?
- react-native - 当声明为 webpack 外部时,React Native WebView 无法加载 React
- .htaccess - htaccess 在三个值中解码 url
- php - Foreach 循环仅将第一个条目放入表中,然后将其移出
- r - R summarize ignores group by and drops column
- go - CrytoJs.AES encrypt/decrypt in golang
- reactjs - 材料ui网格内的水平滚动反应
- python - GAE 迁移到 Python3 google auth 库导入问题