How to use caching in ASP.NET Web API?

試著忘記壹切 提交于 2019-11-27 11:46:22

Unfortunately, caching is not built into ASP.NET Web API.

Check this out to get you on track: http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/

An updated resource here: https://github.com/filipw/AspNetWebApi-OutputCache

Add a reference to System.Runtime.Caching in your project. Add a helper class :

using System;
using System.Runtime.Caching;


public static class MemoryCacher
{
    public static object GetValue(string key)
    {
        MemoryCache memoryCache = MemoryCache.Default;
        return memoryCache.Get(key);
    }

    public static bool Add(string key, object value, DateTimeOffset absExpiration)
    {
        MemoryCache memoryCache = MemoryCache.Default;
        return memoryCache.Add(key, value, absExpiration);
    }

    public static  void Delete(string key)
    {
        MemoryCache memoryCache = MemoryCache.Default;
        if (memoryCache.Contains(key))
        {
            memoryCache.Remove(key);
        }
    }
}

Then from your code get or set objects in the cache :

list = (List <ChapterEx>)MemoryCacher.GetValue("CacheItem1");

and

MemoryCacher.Add("CacheItem1", list, DateTimeOffset.UtcNow.AddYears(1));

As already mentioned by OakNinja, output caching via [OutputCache] attributes is currently not supported by the ASP.NET Web API.

However, there are a few open source implementations filling the gap:

Strathweb.CacheOutput

A small library bringing caching options, similar to MVC's "OutputCacheAttribute", to Web API actions.

Github: https://github.com/filipw/Strathweb.CacheOutput
License: Apache v2

CacheCow

An implementation of HTTP Caching in ASP.NET Web API for both client-side and server-side.

Github: https://github.com/aliostad/CacheCow
License: MIT

Note: According to the projects README, the library does not support attribute routing:

Currently CacheCow's attribute setting does not work with Attribute Routing. And I personally think you should not use Attribute Routing... (Source: https://github.com/aliostad/CacheCow/blob/master/README.md)

There is a nice blog post by Scott Hanselmann covering both feature sets.

wonster

[ResponseCache] is now supported in ASP.NET Core

Features may look identical to [OutputCache] but [ResponseCache] is only for the client side.

Response caching adds cache-related headers to responses. These headers specify how you want client, proxy and middleware to cache responses.

https://docs.microsoft.com/en-us/aspnet/core/performance/caching/response

[ResponseCache(Duration = 3600)]
[HttpGet]
public IEnumerable<Product> Get()
{
  return _service.GetAll();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!