0

我想使用 ASP.NET 最小 API 为不同的端点返回不同的缓存控制标头值。我们如何在没有控制器的情况下做到这一点?

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

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

第一个端点返回标头Cache-Control: public,max-age=3600

第二个端点返回标头Cache-Control: no-cache,max-age=0

4

1 回答 1

0

您可以使用允许您与 and 交互的重载,RequestDelegate以便您可以设置缓存标头,如下所示:HttpContextHttpResponse

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!");
});
于 2022-01-31T18:34:39.843 回答