0

I have a project that has both MVC controllers and WebApi controllers. I am using System.Web.HttpContext.Current.Cache to store some static data so it is not retrieved from the database for every request. It looks like the WebApi controllers do not see the data cached by the MVC controllers. Do they use a different instance of System.Web.HttpContext.Current.Cache?

Thanks, Bert-Jan

Bert-Jan
  • 31
  • 4
  • For the record, you should never reference the static `System.Web.HttpContext.Current` instance directly within MVC/Web API. You should only use the wrapped `HttpContextBase` instance that is passed into controllers/filters. I am not sure if this will fix your problem, though. – NightOwl888 Feb 25 '17 at 17:08
  • Thanks. I ran some tests and the this cache is available in WebApi and MVC controllers and they can see each other's cached items. I was mistaken. Thanks for pointing out the wrapped HttpContextBase. Out of interest: what is the danger with referencing the static instance? – Bert-Jan Feb 26 '17 at 13:15
  • The main issue is the same as when you reference any static method - tight coupling. For example, there is no way to mock the static `System.Web.HttpContext.Current` instance in a unit test, but you *can* mock the `HttpContextBase`. Not to mention, MVC *might* alter some of the values that are passed through the wrapper - if you don't reference it, you might introduce subtle bugs into your application. – NightOwl888 Feb 26 '17 at 13:23

1 Answers1

0

I think that this answer will help you. WebAPI HttpContext Cache - is it possible?

Community
  • 1
  • 1
Qwerty Qwerty
  • 581
  • 1
  • 6
  • 19