如何使用 ASP.NET 最小 API 为不同端点 return 不同 cache-control headers?

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

我想 return 使用 ASP.NET 最小 API 为不同的端点提供不同的 cache-control header 值。我们如何在没有控制器的情况下做到这一点?

这可以使用如下控制器来完成:

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

第一个端点 return 是 header Cache-Control: public,max-age=3600

第二个端点 return 是 header Cache-Control: no-cache,max-age=0

您可以使用 RequestDelegate overload,它允许您与 HttpContextHttpResponse 交互,这样您就可以设置缓存 headers,像这样:

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

您可以编写一个简单的扩展方法来为您添加,例如

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";
    }
}

...这使您的最小 API 方法不那么冗长:

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

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