将数据传递到更进一步的中间件 [英] Pass data to middleware further down the chain
问题描述
当我将中间件注册为请求管道的一部分时,如何通过中间件链传递数据. (最终可通过MVC控制器操作访问)
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)
例如,我已经实现了用于对请求进行身份验证的自定义中间件,但是如何将身份验证数据(例如,身份验证和其他数据的结果)传递到中间件链的下游-最终希望从MVC控制器操作,以及用于基于身份验证结果限制访问的自定义MVC操作过滤器.
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?
推荐答案
您可以使用HttpContext.Items
集合存储请求生存期内的数据.它的主要用例是在组件(例如中间件和控制器)之间传递数据.添加和阅读项目很容易:
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:
写:
context.Items["AuthData"] = authData;
阅读:
var authData = (AuthData)context.Items["AuthData"];
请参见 ASP.NET文档有关更多信息.
这篇关于将数据传递到更进一步的中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!