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