Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data to middleware further down the chain

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?

like image 534
Warrick Avatar asked Aug 10 '16 07:08

Warrick


People also ask

What is a pipeline of middleware?

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.

What happens when a terminal middleware is used in the request 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.

How can we configure the pipeline for middleware?

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.

What is difference between middleware and filters in .NET Core?

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.


2 Answers

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.

like image 71
Henk Mollema Avatar answered Oct 19 '22 06:10

Henk Mollema


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");
like image 44
Xudong Jin Avatar answered Oct 19 '22 05:10

Xudong Jin