10

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

1 Answer 1

10

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"
Sign up to request clarification or add additional context in comments.

1 Comment

I've run into this also. Although the RFC requires this behavior for a cache when a browser request has a no-cache/no-store header, it really only makes sense for an intermediary cache like an ISP or CDN. The server shouldn't be forced to re-render if it's the owner of the content & knows it hasn't changed. Here's an extension I wrote which allows you to turn off this default behavior of ASP.Net Core's ResponseCache: github.com/speige/AspNetCore.ResponseCaching.Extensions nuget.org/packages/AspNetCore.ResponseCaching.Extensions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.