简体   繁体   中英

How to pass primitive data to asp.net core middleware

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

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

eg 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? eg 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?

thanks

Let's suppose we have a middleware:

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

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

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

You could create a DTO and pass it:

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

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM