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



在传统的 ASP.NET 应用程序(使用System.Web)中,我可以将数据缓存在

HttpContext.Current.Items 

现在在Owin中,HttpContext不再可用。有没有办法在 Owin 中做类似的事情 - 一种静态方法/属性,我可以通过它设置/获取每个请求的数据

这个问题给出了一些提示,但在我的情况下并不是确切的解决方案。

最后我找到了OwinRequestScopeContext。使用起来非常简单。

在启动类中:

app.UseRequestScopeContext();

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

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

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

var currentClient = OwinRequestScopeContext.Current.Items["myclient"] as Client;

如果你好奇,这里是源代码。它使用 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");

最新更新