设置到期/缓存头在Web API格式化 [英] Setting Expires/Caching headers in a Web API Formatter
问题描述
时,可以设置在网页API一个MediaTypeFormatter内到期/缓存头?我曾尝试重写SetDefaultContentHeaders和设置像这样expires头:
Is is possible to set the expiration/caching headers inside of a MediaTypeFormatter in Web API? I have tried overriding the SetDefaultContentHeaders and setting the expires header like so:
public override void SetDefaultContentHeaders(Type type, System.Net.Http.Headers.HttpContentHeaders headers, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
{
headers.Expires = DateTime.Now.AddHours(24);
}
但到期的Web调试像Chrome的工具查看时,它的头总是回来为-1。它也不会出现在设定CacheControl头这里不可能,因为这是一个响应头,而不是一个内容标题(无论该装置)。
But the expires header always comes back with -1 when viewing it in a web debugger like the Chrome tools. It also doesn't appear that setting the CacheControl header is not possible here as that is a response header and not a content header (whatever that means).
推荐答案
好像的任何设置的Htt presponseMessage.Headers.CacheControl
将要到期发射头作为集,但没有它设置过期时间发出与值-1。尝试设置 response.Headers.CacheControl =新CacheControlHeaderValue()
不过的没有设置最大年龄的。你应该能够做到这一点的任何地方,它公开的Htt presponseMessage
;例如在 ApiController
或 DelegatingHandler
。
Seems any setting of HttpResponseMessage.Headers.CacheControl
causes the Expires header to be emitted as set, but without it set Expires is emitted with a value of -1. Try setting response.Headers.CacheControl = new CacheControlHeaderValue()
but without setting max-age. You should be able to do this anywhere that exposes HttpResponseMessage
; e.g. in the ApiController
or a DelegatingHandler
.
根据 RFC2616 ,如果CacheControl的最大年龄为present,它将覆盖到期,但如果你只是把它设置为高于它应该工作。
As per RFC2616, if CacheControl's max-age is present, it overrides Expires, but if you just set it as above it should work.
不管这是一个好主意是值得商榷的,因为到期时HTTP 1.0,而CacheControl是HTTP 1.1。
Whether or not this is a good idea is debatable, as Expires is HTTP 1.0, while CacheControl is HTTP 1.1.
这篇关于设置到期/缓存头在Web API格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!