如何为所有WebApi响应禁用缓存,以避免IE使用(从缓存)响应 [英] How to disable caching for all WebApi responses in order to avoid IE using (from cache) responses

查看:44
本文介绍了如何为所有WebApi响应禁用缓存,以避免IE使用(从缓存)响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
    }
}

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

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

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

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

In IE11, I only get the cached result.

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

推荐答案

您可以添加

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

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

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

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

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

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

请参见文档中的ResponseCache属性以获取更多信息.

See ResponseCache attribute in the docs for more information.

这篇关于如何为所有WebApi响应禁用缓存,以避免IE使用(从缓存)响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆