【问题标题】:Data caching per request in Owin applicationOwin 应用程序中每个请求的数据缓存
【发布时间】:2017-04-22 01:23:52
【问题描述】:

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

中缓存数据
HttpContext.Current.Items 

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

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

【问题讨论】:

  • 很好的问题...

标签: asp.net owin


【解决方案1】:

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

在 Startup 类中:

app.UseRequestScopeContext();

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

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

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

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

Here 是源代码,如果你好奇的话。它使用 CallContext.LogicalGetData 和 LogicalSetData。有人认为这种缓存请求数据的方法有什么问题吗?

【讨论】:

  • 我对这个答案投了赞成票,因为;这是我不知道的一种新方法。我一直使用DalSoft 的方法。有谁知道两者的区别?这种方法似乎更全局,而 DalSoft 的方法似乎更本地,但我仍然不确定其中的区别。
  • OwinRequestScopeContext.Current 始终为空。请帮忙。
  • 在 startup.cs 中,在启用 WebApi 之前调用 app.UseRequestScopeContext() - 或将其放在最顶部。
【解决方案2】:

您只需要为此使用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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    相关资源
    最近更新 更多