在传统的ASP.NET应用程序(使用System.Web)中,我能够缓存数据
HttpContext.Current.Items
Run Code Online (Sandbox Code Playgroud)
现在在Owin中,HttpContext不再可用.有没有办法在Owin中做类似的事情 - 一个静态方法/属性,通过它我可以设置/获取每个请求数据?
这个问题提供了一些提示,但在我的案例中并没有确切的解决方案.
Cal*_*vin 18
最后我找到了OwinRequestScopeContext.使用非常简单.
在Startup类中:
app.UseRequestScopeContext();
Run Code Online (Sandbox Code Playgroud)
然后我可以像这样添加每个请求缓存:
OwinRequestScopeContext.Current.Items["myclient"] = new Client();
Run Code Online (Sandbox Code Playgroud)
然后我可以在我的代码中的任何地方(就像HttpContext.Current):
var currentClient = OwinRequestScopeContext.Current.Items["myclient"] as Client;
Run Code Online (Sandbox Code Playgroud)
如果你很好奇,这是源代码.它使用CallContext.LogicalGetData和LogicalSetData.有没有人看到这种缓存请求数据的方法有任何问题?
Dal*_*oft 14
你只需要使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
来自MVC或WebApi:
Request.GetOwinContext().Get<string>("Hello");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6432 次 |
| 最近记录: |