Kontakt oss
Tilbake til bloggen
Innsikt

Avoid browser loading cached api result

How to prevent browsers from fetching cached API results when navigating back, using a custom ActionFilterAttribute in C#.

Recently we had a customer reporting an issue were the content of page was not fully loaded. Initially we had some trouble reproducing this, but with good help from the customer we discovered that the issue only happened when the user navigated back to previous page using the browser back button.

After verifying that page events and scripts were running without errors, we realized that issue was related to the result of an api call.
It turned out that the browser fetched a cached result of an api call (from disk cache) - the result belonging to the previous page.

The solution to this issue was to create a custom ActionFilterAttribute to add to the api method in question.

 public class NoCacheAttribute : ActionFilterAttribute { public override void OnActionExecuted( HttpActionExecutedContext actionExecutedContext) { var response = actionExecutedContext?.Response; var headers = response?.Headers; if (headers == null) return; headers.CacheControl = new CacheControlHeaderValue { NoCache = true, MustRevalidate = true, NoStore = true, }; headers.Add("Pragma", "no-cache"); var contentHeaders = response.Content.Headers; contentHeaders.Expires = DateTimeOffset.Now; base.OnActionExecuted(actionExecutedContext); } }

And then using that attribute on the api method:

[System.Web.Http.HttpGet] [NoCache] public IHttpActionResult MyMethod() { }

Snakk med oss

Har du et prosjekt vi kan hjelpe med?

Ta en uforpliktende prat med teamet vårt om hvordan vi kan løse din utfordring.

Ta kontakt

Hold deg oppdatert på fremtidens e-handel

Ukentlige analyser, trender og praktiske råd — kun det vi selv ville lest.