【问题标题】:How to disable caching for all WebApi responses in order to avoid IE using (from cache) responses如何禁用所有 WebApi 响应的缓存以避免 IE 使用(来自缓存)响应
【发布时间】:2019-09-05 05:08:21
【问题描述】:

我有一个简单的 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 从 Angular 应用程序查询此操作时:

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

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

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

【问题讨论】:

    标签: c# caching asp.net-core asp.net-core-webapi http-caching


    【解决方案1】:

    您可以将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

    【讨论】:

      猜你喜欢
      • 2012-05-09
      • 2012-04-10
      • 2019-05-06
      • 1970-01-01
      • 2017-12-29
      • 2020-08-19
      • 2011-10-15
      • 1970-01-01
      相关资源
      最近更新 更多