26

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?

Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
Warrick
  • 1,623
  • 1
  • 17
  • 20
  • If you want to add extra claims to current principal(as far as i understand your example), you can use `Claims Transformation`. – adem caglin Aug 10 '16 at 08:05

2 Answers2

42

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.

Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
2

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");
Xudong Jin
  • 99
  • 1
  • 2