簡體   English   中英

在 Web API 中設置 HTTP 緩存控制標頭

[英]Setting HTTP cache control headers in Web API

在 WebAPI 中為公共緩存服務器設置緩存控制標頭的最佳方法是什么?

我對服務器上的 OutputCache 控制不感興趣,我希望控制 CDN 端及其他地方的緩存(我有單獨的 API 調用,其中可以為給定的 URL 無限期地緩存響應)但是我讀過的所有內容都是如此far 要么引用了 WebAPI 的預發布版本(因此引用了似乎不再存在的東西,例如 System.Web.HttpContext.Current.Reponse.Headers.CacheControl),或者只是設置幾個 http 標頭似乎非常復雜。

有沒有一種簡單的方法可以做到這一點?

正如評論中所建議的,您可以創建一個 ActionFilterAttribute。 這是一個僅處理 MaxAge 屬性的簡單方法:

public class CacheControlAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public int MaxAge { get; set; }

    public CacheControlAttribute()
    {
        MaxAge = 3600;
    }

    public override void OnActionExecuted(HttpActionExecutedContext context)
    {
        if (context.Response != null)
            context.Response.Headers.CacheControl = new CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(MaxAge)
            };

        base.OnActionExecuted(context);
    }
}

然后你可以將它應用到你的方法中:

 [CacheControl(MaxAge = 60)]
 public string GetFoo(int id)
 {
    // ...
 }

緩存控制頭可以這樣設置。

public HttpResponseMessage GetFoo(int id)
{
    var foo = _FooRepository.GetFoo(id);
    var response = Request.CreateResponse(HttpStatusCode.OK, foo);
    response.Headers.CacheControl = new CacheControlHeaderValue()
        {
            Public = true,
            MaxAge = new TimeSpan(1, 0, 0, 0)
        };
    return response;
}

如果有人在這里尋找專門針對 ASP.NET Core 的答案,您現在可以執行 @Jacob 建議的操作,而無需編寫自己的過濾器。 核心已經包括這個:

[ResponseCache(VaryByHeader = "User-Agent", Duration = 1800)]
public async Task<JsonResult> GetData()
{
}

https://docs.microsoft.com/en-us/aspnet/core/performance/caching/response

就像這個建議過濾器的答案一樣,請考慮“擴展”版本——http: //www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/

它曾經作為 NuGet 包Strathweb.CacheOutput.WebApi2 ,但似乎不再托管,而是在 GitHub 上 -- https://github.com/filipw/AspNetWebApi-OutputCache

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM