ASP.NET Core 2.0 Web API响应缓存

10

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

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

正确的标头使用指定的最大年龄生成,但是Postman似乎从API请求响应而不是使用缓存。响应时间根本不变,如果我调试控制器,我可以看到每次请求都会命中它。

Startup类ConfigureServices方法(以及其他内容):

services.AddResponseCaching();

启动类Configure(以及其他内容):

 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
1个回答

10

问题已经解决。上面的代码没问题!

是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 - Devin Garner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接