我需要将一些数据传递到 ASP NET CORE 中间件
例如如果这是一个字符串列表,您是否使用与传入服务相同的机制?
例如将其作为参数添加到 Invoke 方法中并注册到 DI?
如果是这样,你如何注册原始类型?例如一串字符串。它必须是命名类型或类似的东西吗?
或者我们可以通过其他方式传递数据吗?
谢谢
最佳答案
假设我们有一个中间件:
public class FooMiddleware
{
public FooMiddleware(RequestDelegate next, List<string> list)
{
_next = next;
}
}
只需将列表传递给 UseMiddleware
调用即可per-middleware 解决它:
app.UseMiddleware<FooMiddleware>(new List<string>());
您可以创建一个 DTO 并传递它:
public FooMiddleware(RequestDelegate next, Payload payload)
....
app.UseMiddleware<FooMiddleware>(new Payload());
或者在DI容器中注册这个DTO,在中间件中解析:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Payload>(new Payload());
}
此外,DI 容器允许解析每个请求 依赖项:
public async Task Invoke(HttpContext httpContext, IMyScopedService svc)
{
svc.MyProperty = 1000;
await _next(httpContext);
}
Because middleware is constructed at app startup, not per-request, scoped lifetime services used by middleware constructors are not shared with other dependency-injected types during each request. If you must share a scoped service between your middleware and other types, add these services to the
Invoke
method's signature. TheInvoke
method can accept additional parameters that are populated by dependency injection.
关于c# - 如何将原始数据传递给 asp.net core 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44501028/