WebAPI core 2.0 Cache by post params

299 Views Asked by At

I am building an pure json api and I want to cache response according to post params. Is there any similar way like VaryByQueryKeys? Maybe some custom cache middleware or?

Of course I can use MemoryCache but wonder maybe there is some "build in" practice.

2

There are 2 best solutions below

0
On

Of course shouldn't expect caching in post API

But look at this sample code on special controller not in middleware and it is not "build in"

May be useful

  public class XController : Controller
   {
    private readonly IMemoryCache _cache;
    public XController(IMemoryCache cache)
    {
        _cache = cache;
    }

    [HttpPost]
    public async Task<IEnumerable<YourCustomModel>> Post([FromBody] ParamtersModel value)
    {
        string cacheKey = value.Id.ToString();
        IEnumerable<YourCustomModel> cacheEntry = await _cache.GetOrCreate(cacheKey, async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60);
           
            IEnumerable<YourCustomModel> result = await ... your method calling for first time to getting in cache
            return result;

        });
        return cacheEntry;
    }

   }
3
On

Check this thread here: WebAPI caching for http Post

Do you really need HttpPost request to fulfill your requirements? Have you considered using GET request and then leverage client side caching?