Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable caching for all WebApi responses in order to avoid IE using (from cache) responses

I have a simple ASP.NET Core 2.2 Web Api controller:

[ApiVersion("1.0")]
[Route("api/[controller]")]
[ApiController]
public class TestScenariosController : Controller
{
   [HttpGet("v2")]
    public ActionResult<List<TestScenarioItem>> GetAll()
    {
        var entities = _dbContext.TestScenarios.AsNoTracking().Select(e => new TestScenarioItem
        {
            Id = e.Id,
            Name = e.Name,
            Description = e.Description,
        }).ToList();

        return entities;
    }
}

When I query this action from angular app using @angular/common/http:

this.http.get<TestScenarioItem[]>(`${this.baseUrl}/api/TestScenarios/v2`);

In IE11, I only get the cached result.

How do I disable cache for all web api responses?

enter image description here

enter image description here

like image 257
Liero Avatar asked Apr 15 '19 08:04

Liero


1 Answers

You can add ResponseCacheAttribute to the controller, like this:

[ApiVersion("1.0")]
[Route("api/[controller]")]
[ApiController]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public class TestScenariosController : Controller
{
    ...
}

Alternatively, you can add ResponseCacheAttribute as a global filter, like this:

services
    .AddMvc(o =>
    {
        o.Filters.Add(new ResponseCacheAttribute { NoStore = true, Location = ResponseCacheLocation.None });
    });

This disables all caching for MVC requests and can be overridden per controller/action by applying ResponseCacheAttribute again to the desired controller/action.

See ResponseCache attribute in the docs for more information.

like image 75
Kirk Larkin Avatar answered Sep 20 '22 23:09

Kirk Larkin