Reputation: 14552
I want to use a custom DelegatingHandler to add the E-Tag header to responses for some of my Web API calls. Here is part of my SendAsync()
override:
if (request.Method == HttpMethod.Get)
{
HttpResponseMessage response;
if (request.Headers.IfNoneMatch.Count == 0)
{
response = await base.SendAsync(request, cancellationToken);
response.Headers.Add("X-MyStupidTestHeader","It's here"); //<- this is always on my responses
response.Content.Headers.Expires = DateTimeOffset.Now.AddMinutes(10.0);
var tag = TagStore.Fetch(request.RequestUri); // <- this is non-null
if (tag != null)
response.Headers.ETag = new EntityTagHeaderValue(tag); //<- this is nowhere to be found. WTF?
return response;
}
...
}
When I call that url in the browser with Fiddler listening I get the following response:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Wed, 10 Jul 2013 16:08:00 GMT
X-AspNet-Version: 4.0.30319
X-MyStupidTestHeader: It's here
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: text/html; charset=utf-8
Content-Length: 18
Connection: Close
{
"carId": 2
}
I know my DelegatingHandler is getting called, because I've set the breakpoints. On the way out of my SendAsync
override, the response has an E-Tag value; but then when it comes out of the server, it's not there and all these caching headers are there, telling the client not to cache. All my googling suggests that it's up to me to set up caching, which is fine, but how do I stop the Web API from not caching?
Update: I realize there are libraries for this sort of thing, but I'd rather not use them for this.
Upvotes: 2
Views: 3325
Reputation: 19311
ETag header is not getting written into the response because you are not using caching. This behavior is specific only to Visual Studio development server. If you deploy in IIS, you will see the ETag header in response with your handler code.
Even with Visual Studio development server, if you enable caching, the ETag header will be in the response.
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromSeconds(60),
MustRevalidate = true,
Private = true
};
Upvotes: 3