如何将原始数据传递给asp.net核心中间件 [英] How to pass primitive data to asp.net core middleware

查看:118
本文介绍了如何将原始数据传递给asp.net核心中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些数据传递到ASP NET CORE中间件

I need to pass some data into a ASP NET CORE middleware

例如如果这是一个字符串列表,那么您使用与传递服务相同的机制吗?

e.g. if this is a list of strings, do you use the same mechanism as passing in a service?

例如将它作为参数添加到Invoke方法中,并向DI注册吗?

e.g. add it as a parameter to the Invoke method and register it with the DI?

如果是这样,您如何注册原始类型?例如一声不响.它必须是命名类型还是类似的名称?

If so, how do you do the registration for primitive types? e.g. a lsit of strings. does it have to be a named type or something like that?

或者我们可以通过其他方式传递数据吗?

Or can we pass the data in some other way?

谢谢

推荐答案

让我们假设我们有一个中间件:

Let's suppose we have a middleware:

public class FooMiddleware
{
    public FooMiddleware(RequestDelegate next, List<string> list)
    {
        _next = next;
    }
}

只需将列表传递给 UseMiddleware 调用即可解决每个中间件:

Just pass a list to UseMiddleware call to resolve it per-middleware:

app.UseMiddleware<FooMiddleware>(new List<string>());

您可以创建一个DTO并通过它:

You could create a DTO and pass it:

public FooMiddleware(RequestDelegate next, Payload payload)
....
app.UseMiddleware<FooMiddleware>(new Payload());    

或将此DTO注册到DI容器中,它将在中间件中解决:

Or register this DTO in DI container, it will be resolved in middleware:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<Payload>(new Payload());
}

此外,DI容器允许解析每个请求依赖关系:

In addition, DI container allows to resolve per-request dependencies:

public async Task Invoke(HttpContext httpContext, IMyScopedService svc)
{
    svc.MyProperty = 1000;
    await _next(httpContext);
}

文档:

因为中间件是在应用启动时构建的,而不是按请求构建的,在每次请求期间,中间件构造函数使用的作用域生存期服务不会与其他依赖项注入类型共享.如果您必须在中间件和其他中间件之间共享作用域服务类型,请将这些服务添加到 Invoke 方法的签名中.这 Invoke 方法可以接受由填充的其他参数依赖注入.

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.

这篇关于如何将原始数据传递给asp.net核心中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆