【问题标题】:ASP.NET Core 2.0 Web API Response CachingASP.NET Core 2.0 Web API 响应缓存
【发布时间】:2018-02-08 03:33:46
【问题描述】:

我正在尝试使用“Microsoft.AspNetCore.ResponseCaching”包在我的 Web api 中实现响应缓存。

我正在使用 Postman 来测试应用程序并验证标头等。

使用指定的 max-age 生成正确的标头,但邮递员似乎从 api 请求响应而不使用缓存。响应时间根本没有变化,如果我调试控制器,我可以看到它每次都被请求击中。

启动类 ConfigureServices(以及其他东西):

services.AddResponseCaching();

启动类配置(以及其他东西):

 app.UseResponseCaching();

 app.UseMvc();

控制器动作:

    [HttpGet("{employeeNr}", Name = EmployeeAction)]
    [ResponseCache(Duration = 50)]
    [Produces(typeof(EmployeeDto))]
    public async Task<IActionResult> GetEmployee(SpecificEmployeeParameters parameters)
    {
        if (!await _employeeRepository.EmployeeExists(parameters.EmployeeNr)) return NotFound();

        if (!_typeHelperService.TypeHasProperties<EmployeeDto>(parameters.Fields))
            return BadRequest();

        var entity = await _employeeRepository.GetEmployee(parameters.EmployeeNr);

        var result = Mapper.Map<EmployeeDto>(entity);
        return Ok(result.ShapeData(parameters.Fields));
    }

来自 Postman 的响应标头:

cache-control →private,max-age=50
content-type →application/json; charset=utf-8
date →Wed, 30 Aug 2017 11:53:06 GMT

【问题讨论】:

    标签: caching asp.net-core asp.net-core-webapi


    【解决方案1】:

    解决了这个问题。上面的代码没问题! Postman 正在通过设置阻止缓存。

    要解决此问题,请转到 Postman 设置:

    General -> Headers -> Send no-cache header -> Set to "OFF"
    

    【讨论】:

    • 我也遇到过这个问题。尽管 RFC 要求当浏览器请求具有 no-cache/no-store 标头时缓存具有这种行为,但它实际上只对像 ISP 或 CDN 这样的中间缓存有意义。如果服务器是内容的所有者并且知道它没有更改,则不应强制服务器重新渲染。这是我编写的一个扩展,它允许您关闭 ASP.Net Core 的 ResponseCache 的默认行为:github.com/speige/AspNetCore.ResponseCaching.Extensions nuget.org/packages/AspNetCore.ResponseCaching.Extensions
    猜你喜欢
    • 2018-03-11
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    相关资源
    最近更新 更多