C# 在 Web API 中设置 HTTP 缓存控制标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15911356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:26:23  来源:igfitidea点击:

Setting HTTP cache control headers in Web API

c#asp.net-web-apihttp-caching

提问by Moo

What's the best way to set cache control headers for public caching servers in WebAPI?

在 WebAPI 中为公共缓存服务器设置缓存控制标头的最佳方法是什么?

I'm not interested in OutputCache control on my server, I'm looking to control caching at the CDN side and beyond (I have individual API calls where the response can be indefinitely cached for the given URL) but everything I've read thus far either references pre-release versions of WebAPI (and thus references things that seem to no longer exist, like System.Web.HttpContext.Current.Reponse.Headers.CacheControl) or seems massively complicated for just setting a couple of http headers.

我对服务器上的 OutputCache 控制不感兴趣,我希望控制 CDN 端及其他地方的缓存(我有单独的 API 调用,其中可以为给定的 URL 无限期地缓存响应)但是我读过的所有内容都是如此far 要么引用了 WebAPI 的预发布版本(因此引用了似乎不再存在的东西,例如 System.Web.HttpContext.Current.Reponse.Headers.CacheControl),或者只是设置几个 http 标头似乎非常复杂。

Is there a simple way to do this?

有没有一种简单的方法可以做到这一点?

采纳答案by Darrel Miller

The cache control header can be set like this.

缓存控制头可以这样设置。

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

回答by Jacob

As suggested in the comments, you can create an ActionFilterAttribute. Here's a simple one that only handles the MaxAge property:

正如评论中所建议的,您可以创建一个 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);
    }
}

Then you can apply it to your methods:

然后你可以将它应用到你的方法中:

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

回答by drzaus

Like this answersuggesting filters, consider the "extended" version -- http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/

就像这个建议过滤器的答案一样,请考虑“扩展”版本——http: //www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/

It used to be available as a NuGet package Strathweb.CacheOutput.WebApi2, but doesn't seem to be hosted anymore, and is instead on GitHub -- https://github.com/filipw/AspNetWebApi-OutputCache

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

回答by mattferderer

In case anyone lands here looking for an answer specifically to ASP.NET Core, you can now do what @Jacob suggested without writing your own filter. Core already includes this:

如果有人在这里寻找专门针对 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

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