Nash
Nash

Reputation: 531

Control Cache from Front End

I would like to control the cache from the front end when certain calls are made in PracticeUpdate.

For example, when calling /api/GetAllTags from the javascript function GetAllTags, I can see in Fiddler that the return header for cache-control is set to no-cache. Is it possible to modify this in the api?

Upvotes: 0

Views: 159

Answers (2)

Aliostad
Aliostad

Reputation: 81660

Default caching policy for Web API is no caching.

You can add the caching into each action or just use a framework to do that for you such as CacheCow which is full implementation of HTTP caching in both client (when you use HttpClient) and server.

Upvotes: 0

Nick
Nick

Reputation: 6588

All you need to do is get Access to the HttpResponseMessage object of the request. You can do this inside a controller action by asking the Request property of the controller to create the response for you:

var response = Request.CreateResponse(HttpStatusCode.OK);

Then you can access the CacheControl object via the Headers like so:

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

You could also make use of an ActionFilter in this scenario, so caching can be applied to an ApiController Action method via an attribute:

public class HttpCacheForMinutesAttribute : ActionFilterAttribute
{
    private readonly int _duration;

    public HttpCacheForMinutesAttribute(int duration)
    {
        _duration = duration;
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnActionExecuted(actionExecutedContext);

        actionExecutedContext.Response.Headers.CacheControl = new CacheControlHeaderValue
        {
            Public = true, MaxAge = TimeSpan.FromMinutes(_duration)
        };
    }
}

Upvotes: 2

Related Questions