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

On Which Request can we apply Request Caching?

  1. Get
  2. Head

Constraints for Response Caching

Real-world Examples of Response Caching?

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?