在一个中间件中定义一个变量,可用于下列变量
问题描述:
我使用的是asp.net核心,并且我希望在调用完整的Web应用程序之前从请求中获取多个数据。在一个中间件中定义一个变量,可用于下列变量
所以我创建了一个中间件来做到这一点。我发现了一个方法来检查我想要的一切,但我不知道如何将一个变量传递给下面的中间件
app.Use(async (context, next) => {
var requestInfo = GetRequestInfo(context.Request);
if(requestInfo == null)
{
context.Response.StatusCode = 404;
return;
}
// How do I make the request info available to the following middlewares ?
await next();
});
app.Run(async (context) =>
{
// var requestInfo = ???
await context.Response.WriteAsync("Hello World! - " + env.EnvironmentName);
});
是否有从中间件到别人传递数据的好办法? (这里我用app.Run
,但我想有这一切,MVC)
答
我找到了解决办法:上下文包含IFeatureCollection
和it is documented here
我们只需要创建一个类的所有数据:
public class RequestInfo
{
public String Info1 { get; set; }
public int Info2 { get; set; }
}
,我们把它添加到context.Features
:
app.Use(async (context, next) => {
RequestInfo requestInfo = GetRequestInfo(context.Request);
if(requestInfo == null)
{
context.Response.StatusCode = 404;
return;
}
// We add it to the Features collection
context.Features.Set(requestInfo)
await next();
});
现在是提供给OTH ERS中间件:
app.Run(async (context) =>
{
var requestInfo = context.Features.Get<RequestInfo>();
});
哦,这是更简单,是的! – glacasa