[SOLVED] How to return different cache-control headers for different endpoints using ASP.NET minimal APIs?

Issue

I would like to return a different cache-control header value for different endpoints using ASP.NET minimal APIs. How do we do this without controllers?

This can be accomplished using controllers as follows:

using Microsoft.AspNetCore.Mvc;

namespace CacheTest;

[ApiController]
public class TestController : ControllerBase
{
    [HttpGet, Route("cache"), ResponseCache(Duration = 3600)]
    public ActionResult GetCache() => Ok("cache");

    [HttpGet, Route("nocache"), ResponseCache(Location = ResponseCacheLocation.None, Duration = 0)]
    public ActionResult GetNoCache() => Ok("no cache");
}

The first endpoint returns the header Cache-Control: public,max-age=3600.

The second endpoint returns the header Cache-Control: no-cache,max-age=0.

Solution

You can use the RequestDelegate overload which allows you to interact with the HttpContext and HttpResponse so that you can set cache headers, like this:

app.MapGet("/", httpContext =>  
{
    httpContext.Response.Headers[HeaderNames.CacheControl] =
        "public,max-age=" + 3600;
    return Task.FromResult("Hello World!");
});

You could write a simple extension method to add that for you, like

public static class HttpResponseExtensions
{
    public static void AddCache(this HttpResponse response, int seconds)
    {
        response.Headers[HeaderNames.CacheControl] =
            "public,max-age=" + 10000;
    }

    public static void DontCache(this HttpResponse response)
    {
        response.Headers[HeaderNames.CacheControl] = "no-cache";
    }
}

…which makes your minimal API method less verbose:

app.MapGet("/", httpContext =>  
{
    httpContext.Response.AddCache(3600);
    // or
    httpContext.Response.DontCache();

    return Task.FromResult("Hello World!");
});

Answered By – Scott Hannen

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *