When I register middleware as part of the request pipeline, how do I pass data through the middleware chain. (ultimately accessible in an MVC controller action)
For example, I have implemented custom middleware for authenticating my requests, but how can I pass the authentication data (such as the result of the authentication and additional data) down the chain of middleware - ultimately wanting to access the data from an MVC controller action, and also in a custom MVC action filter for restricting access based on the authentication results.
Is there anywhere I can store custom data on a per-request basis, and access it later in the request chain?
Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component: Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline.
Generally, each middleware may handle the incoming requests and passes execution to the next middleware for further processing. But a middleware component can decide not to call the next piece of middleware in the pipeline. This is called short-circuiting or terminate the request pipeline.
Configuring the Request Pipeline To start using any Middleware, we need to add it to the Request pipeline. This is done in the Configure method of the startup class. The Configure method gets the instance of IApplicationBuilder, using which we can register our Middleware.
Middleware vs Filters Filters are a part of MVC, so they are scoped entirely to the MVC middleware. Middleware only has access to the HttpContext and anything added by preceding middleware. In contrast, filters have access to the wider MVC context, so can access routing data and model binding information for example.
You can use the HttpContext.Items
collection to store data for the lifetime of a request. Its primary use-case is passing data around components (middleware and controllers for example). Adding and reading items is easy:
Write:
context.Items["AuthData"] = authData;
Read:
var authData = (AuthData)context.Items["AuthData"];
See the ASP.NET docs for more info.
You can store custom data in IOwinContext object. IOwinContext object can be accessed from Invoke function of your middleware.
Set
context.Set<T>("key", obj);
Get
var obj = context.Get<T>("key");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With