Owin 应用程序中每个请求的数据缓存

Data caching per request in Owin application

在传统的 ASP.NET 应用程序(使用 System.Web)中,我能够在

中缓存数据
HttpContext.Current.Items 

现在在 Owin 中,HttpContext 不再可用。有没有办法在 Owin 中做类似的事情 - static method/property 通过它我可以 set/get per request data?

这个 question 给出了一些提示,但不是我的确切解决方案。

终于找到了OwinRequestScopeContext。使用起来非常简单。

在启动中class:

app.UseRequestScopeContext();

然后我可以像这样添加每个请求缓存:

OwinRequestScopeContext.Current.Items["myclient"] = new Client();

然后我可以在我的代码中的任何地方做(就像 HttpContext.Current):

var currentClient = OwinRequestScopeContext.Current.Items["myclient"] as Client;
如果您好奇的话,

Here 是源代码。它使用 CallContext.LogicalGetData 和 LogicalSetData。有人发现这种缓存请求数据的方法有什么问题吗?

你只需要为此使用 OwinContext:

来自您的中间件:

public class HelloWorldMiddleware : OwinMiddleware
{
   public HelloWorldMiddleware (OwinMiddleware next) : base(next) { }

   public override async Task Invoke(IOwinContext context)
   {   
       context.Set("Hello", "World");
       await Next.Invoke(context);     
   }   
}

来自 MVC 或 WebApi:

Request.GetOwinContext().Get<string>("Hello");