4

I'm trying to cache an ActionResult. In a particular ActionResult I'm writing some data to cookies. The output cache is not working in that action result. Its working fine with all other actions where I'm not using Response.Cookies. Please help me to resolve this issue.

I'm using ASP.NET MVC 4


Edit

(Code included)

 [OutputCache(Duration = 8000, VaryByParam = "*")]
    public ActionResult List(SearchViewModel searchViewModel, int page = 1, int mode = 1)
    {
        HttpCookie ck = Request.Cookies["Geo"];
        string lat = string.IsNullOrEmpty(Request.Params["lat"]) ? null : Request.Params["lat"];
        string lng = string.IsNullOrEmpty(Request.Params["lng"]) ? null : Request.Params["lng"];
        if (ck == null)
        {
            ck = new HttpCookie("Geo");
            Response.Cookies.Add(ck);
        }
        if (lat != null)
        {
            ck["Lat"] = lat;
            ck["Lon"] = lng;
            ck.Expires = DateTime.Now.AddMonths(2);
            Response.Cookies.Set(ck);
//this is the code which causes problem. If I remove this section catching will work
//other logic goes here.. 
        }
     }
Moncy K
  • 59
  • 1
  • 5

2 Answers2

2

Please refer to the Microsoft documentation: https://msdn.microsoft.com/en-us/library/system.web.httpcookie.shareable(v=vs.110).aspx

If a given HttpResponse contains one or more outbound cookies with Shareable is set to false (the default value), output caching will be suppressed for the response. This prevents cookies that contain potentially sensitive information from being cached in the response and sent to multiple clients.

To allow a response containing cookies to be cached, configure caching normally for the response, such as using the OutputCache directive or MVC's [OutputCache] attribute, and set all outbound cookies to have Shareable set to true.

So basically, make sure that you have all your cookies set with:

cookie.Shareable = true; // Needed with Outputcache
webStuff
  • 1,468
  • 14
  • 22
0

I've found an answer in this other question.

It looks as though OutputCache caches the output from a request, so for the same request with the same parameters it won't run the code in the action method, it'll just return the same output. So none of your code will be run on subsequent requests.

It looks like the answer in the other post has some possible work-arounds.

Community
  • 1
  • 1
Adrian Thompson Phillips
  • 6,893
  • 6
  • 38
  • 69