c# - 如何将原始数据传递给 asp.net core 中间件

标签 c# asp.net-core

我需要将一些数据传递到 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);
}

Documentation:

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. The Invoke method can accept additional parameters that are populated by dependency injection.

关于c# - 如何将原始数据传递给 asp.net core 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44501028/

相关文章:

c# - 使用 ServiceStack.Redis,如何在事务中运行强类型只读查询

azure - 如何调试 Azure 应用服务上的启动错误

angular - 在 IIS 默认网站下托管 .Net Core 应用和 Angular 应用

authentication - ASP Core 向 Auth Token 添加自定义声明

c# - 为 Blazor 网站的每个页面使用多种解决方案

c# - 为什么编译器将 Func<dynamic, int> 的返回类型视为强类型?

c# - 同步定时器以防止重叠

c# - 使用多个线程从 mysql 表中读取数据

c# - 在 Core Web API 中通过可选参数删除多条记录的最佳实践是什么?

c# - 最佳实践 : Adding a CLI to Existing Windows Service in . NET/Core