I am just starting with web-api 2 and stumbled upon : how to set caching settings. I have custom caching-message-handler
like below (simplified for SO post)
public class CachingMessageHandler : DelegatingHandler
{
private void SetCachingPolicy(HttpResponseMessage response)
{
response.Headers.CacheControl = new CacheControlHeaderValue
{
MaxAge = TimeSpan.FromSeconds(100),
};
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
return base
.SendAsync(request, cancellationToken)
.ContinueWith(task =>
{
var response = task.Result;
if (request.Method == HttpMethod.Get) SetCachingPolicy(response);
return response;
}, cancellationToken);
}
}
and I have various hello-world HttpGet api's
[HttpGet]
public HttpResponseMessage Get1()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
response.Content = new StringContent("Hello World 1", Encoding.Unicode);
return response;
}
[HttpGet]
public HttpResponseMessage Get2()
{
return Request.CreateResponse(HttpStatusCode.OK, "Hello World 2");
}
[HttpGet]
public HttpResponseMessage Get2_1()
{
var response = Request.CreateResponse(HttpStatusCode.OK, "Hello World 2");
response.Headers.CacheControl = null;
return response;
}
[HttpGet]
public OkNegotiatedContentResult<string> Get3()
{
return Ok("Hello World 3");
}
[HttpGet]
public string Get4()
{
return "Hello World 4";
}
but the caching-message-handler
is applied only for Get1
api, for all other Get2/3/4
api's, it seems some default caching setting is used. Below is the response in postman
Can someone please explain this behavior!!! why is caching only applied for Content-Type : text/plain
and not for application/json