How to cache .NET Web API requests (& use w/ AngularJS $http)

前端 未结 1 1207
忘掉有多难
忘掉有多难 2020-12-24 02:08

I have a Web API written in ASP.NET that I\'m consuming via AngularJS $http.

I have enabled caching in my AngularJS factory as follows but every reques

相关标签:
1条回答
  • 2020-12-24 02:45

    Turns out it was a Web API thing. I'd overlooked the fact that the response header clearly stated that caching was disabled.

    Response as viewed in the Network tab of Google Chrome:

    enter image description here

    Upon further investigation (and as seen in the image above), caching is disabled in Web API controllers. Even the [OutputCache] attribute, which is used in regular MVC controllers, isn't supported.

    Luckily I found this blog: http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/

    which lead me to these two solutions:

    • ASP.NET Web API CacheOutput
    • CacheCow

    I decided to go with CacheOutput as it lets me use attributes like:

    [CacheOutputUntilToday] which supports server & client side caching.

    Or if I wanted to just use client-side caching I can use something like:

    [CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 0)]

    Which seemed a little easier at first glance that CacheCow's approach. And easier to refactor out later if need be.

    Now additional requests give me a 200 (from cache):

    enter image description here

    With a refresh giving me a 304 Not Modified:

    enter image description here

    Problem solved! Hope this helps someone else.

    0 讨论(0)
提交回复
热议问题