如何禁用所有 WebApi 响应的缓存以避免 IE 使用(来自缓存)响应

Lie*_*ero 9 c# caching http-caching asp.net-core asp.net-core-webapi

我有一个简单的 ASP.NET Core 2.2 Web Api 控制器:

[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;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我使用@angular/common/http以下命令从 angular 应用程序查询此操作时:

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

在 IE11 中,我只得到缓存的结果。

如何禁用所有 web api 响应的缓存?

在此处输入图片说明

在此处输入图片说明

Kir*_*kin 15

您可以添加ResponseCacheAttribute到控制器,如下所示:

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

或者,您可以添加ResponseCacheAttribute为全局过滤器,如下所示:

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

这将禁用 MVC 请求的所有缓存,并且可以通过ResponseCacheAttribute再次应用于所需的控制器/操作来覆盖每个控制器/操作。

有关更多信息,请参阅文档中的ResponseCache 属性