Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 2.0 Web API Response Caching

I am trying to implement response caching in my web api using the "Microsoft.AspNetCore.ResponseCaching" package.

I am using Postman to test the application and validate headers etc.

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.

Startup class ConfigureServices (along with other stuff):

services.AddResponseCaching();

Startup class Configure (along with other stuff):

 app.UseResponseCaching();

 app.UseMvc();

Controller Action:

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

Response headers from Postman:

cache-control →private,max-age=50
content-type →application/json; charset=utf-8
date →Wed, 30 Aug 2017 11:53:06 GMT
like image 735
Mr. Toast Avatar asked Aug 30 '17 12:08

Mr. Toast


1 Answers

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"
like image 135
Mr. Toast Avatar answered Sep 25 '22 08:09

Mr. Toast