问题描述
我正在尝试使用"Microsoft.AspNetCore.ResponseCaching"包在Web api中实现响应缓存.
I am trying to implement response caching in my web api using the "Microsoft.AspNetCore.ResponseCaching" package.
我正在使用Postman来测试应用程序并验证标头等.
I am using Postman to test the application and validate headers etc.
使用指定的最大年龄生成正确的标头,但邮递员似乎从api请求响应,而不使用缓存.响应时间完全没有变化,如果我调试控制器,我会看到它每次都被请求击中.
The correct headers are generated with the specified max-age but postman seems to request the response from the api and not using the cache. The response time does not vary at all and if I debug the controller I can see that it gets hit by the request every time.
启动类ConfigureServices(以及其他内容):
Startup class ConfigureServices (along with other stuff):
services.AddResponseCaching();
启动类Configure(以及其他内容):
Startup class Configure (along with other stuff):
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));
}
邮递员的响应标头:
cache-control →private,max-age=50
content-type →application/json; charset=utf-8
date →Wed, 30 Aug 2017 11:53:06 GMT
推荐答案
解决了该问题.上面的代码没问题!邮递员通过设置来阻止缓存.
Fixed the issue. The code above is alright!Postman was preventing caching by a setting.
要解决此问题,请转到邮递员设置:
To fix this behaviour go to Postman Settings:
General -> Headers -> Send no-cache header -> Set to "OFF"
这篇关于ASP.NET Core 2.0 Web API响应缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!