13

In traditional ASP.NET applications (that use System.Web), I'm able to cache data in

HttpContext.Current.Items 

Now in Owin the HttpContext is not available anymore. Is there a way to do the similar thing in Owin - a static method/property through which I can set/get per request data?

This question gave some hints but not exact a solution in my case.

Community
  • 1
  • 1
Calvin
  • 1,153
  • 2
  • 14
  • 25

2 Answers2

18

Finally I found OwinRequestScopeContext. Very simple to use.

In the Startup class:

app.UseRequestScopeContext();

Then I can add per request cache like this:

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

Then anywhere in my code I can do (just like HttpContext.Current):

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

Here is the source code if you're curious. It uses CallContext.LogicalGetData and LogicalSetData. Does any one see any problem with this approach of caching request data?

hbulens
  • 1,872
  • 3
  • 24
  • 45
Calvin
  • 1,153
  • 2
  • 14
  • 25
  • I up-voted this answer because; it is a new approach I was unaware of. I've always used [DalSoft](http://stackoverflow.com/users/324497/dalsoft)'s approach. Does anyone know the difference between the two? This approach seems more **global** while DalSoft's seems a bit more **local**, but I'm still not certain of the difference. – Chef_Code Mar 25 '16 at 20:40
  • 1
    OwinRequestScopeContext.Current is null always. Please help. – Kumar Sep 26 '16 at 07:15
  • In startup.cs, call app.UseRequestScopeContext() before you enable WebApi - or put it at the very top. – Calvin Jan 07 '17 at 00:15
15

You just need to use OwinContext for this:

From your middleware:

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);     
   }   
}

From MVC or WebApi:

Request.GetOwinContext().Get<string>("Hello");
DalSoft
  • 10,673
  • 3
  • 42
  • 55