简体   繁体   中英

ASP.NET Web API action caching

I am trying to cache results of an action in ApiControler and for some reason I am not seeing that something cached. I am not entirely understand how MVC caching works, but I assume if action response been cached than it shouldn't be invoked all the time but it should just output cache if it available.

Action:

    [HttpGet]
    public HttpResponseMessage NetworkStatusSummary()
    {
        // getting networkStatuses
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, networkStatuses);

        response.Headers.CacheControl = new CacheControlHeaderValue {MaxAge = new TimeSpan(0, 10, 0), Public = true};

        return response;
    }

What I am doing wrong here?

Okay, seems nothing fancy built-in Web API. So came up with:

    private IList<NetworkStatus> NetworkStatuses
    {
        get
        {
            IList<NetworkStatus> networkStatuses;
            Cache cache = HttpContext.Current.Cache;

            if (cache[NETWORK_STATUSES_CACHE_KEY] == null)
            {
                networkStatuses = m_networkOwnerService.GetNetworkStatuses();
                cache.Add(NETWORK_STATUSES_CACHE_KEY, networkStatuses, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0), CacheItemPriority.Default, null);
            }
            else
            {
                networkStatuses = (IList<NetworkStatus>) cache[NETWORK_STATUSES_CACHE_KEY];
            }

            return networkStatuses;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM