Response Caching in .Net Web API

Response Caching in .NET Web API

It is a technique for storing the responses of an API in a cache so that they can be served faster to subsequent requests. Responses are stored with a key that uniquely identifies them; the Cache has a limited size and a policy for removing items when it becomes full.

Benefits of Response Caching

  • Improved performance by reducing the load on the server.
  • Reduced server load, as it can serve the cached response instead of generating a new one.
  • Reduced bandwidth usage reduces the amount of data that needs to be transferred between the server and the client.
  • Improved security as it can reduce the number of requests that reach the server, reducing the risk of certain types of attacks.

On Which Request can we apply Request Caching?

  1. Get
  2. Head

Constraints for Response Caching

  • The request must result in a server response with a 200 (OK) status code.
  • Response Caching Middleware must be placed before middleware that requires caching.
  • The Authorization header must not be present.
  • Cache-Control header parameters must be valid, and the response must be marked public and not marked private.
  • The Content-Length header value (if set) must match the size of the response body.

Real-world Examples of Response Caching?

  • News website
  • E-commerce websites

How to Implement It?

// Configure Response Cache Middleware in .Net 6
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCaching();

var app = builder.Build()
app.UseResponseCaching();

How to apply Cache on the Method Level?

[HttpGet("{id}")]
[ResponseCache(Duration =60,Location =ResponseCacheLocation.Client)]
public ActionResult<string> Get(int id)
{
  return "value";
}

How to apply Cache on ControllerLevel?

    [ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

How Can We Verify It?

  • Create an application, apply caching, and then request it from Postman and set the time to 60 minutes; you will notice that only the first request will reach the controller; after that, even if you try request will not reach the controller.

Next Recommended Reading Difference Between API and Web Service