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

问题描述 投票:1回答:1

我有一个简单的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;
    }
}

当我使用@angular/common/http从角度应用程序查询此操作时:

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

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

如何为所有Web api响应禁用缓存?

enter image description here

enter image description here

c# caching asp.net-core asp.net-core-webapi http-caching
1个回答
0
投票

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

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

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

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

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

有关详细信息,请参阅文档中的ResponseCache attribute

© www.soinside.com 2019 - 2024. All rights reserved.