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

雨燕双飞 提交于 2020-12-29 12:21:04

问题


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?


回答1:


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
{
    ...
}

You can instead 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.



来源:https://stackoverflow.com/questions/55685430/how-to-disable-caching-for-all-webapi-responses-in-order-to-avoid-ie-using-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!