2015-03-31 86 views
2

我正在使用此代碼返回對象內容,但我想緩存響應,添加Cache-Control標頭。Web API 2.0 IHttpActionResult高速緩存

[AllowAnonymous] 
[Route("GetPublicContent")] 
[HttpGet] 
public IHttpActionResult GetPublicContent([FromUri]UpdateContentDto dto) 
     { 

      if (dto == null) 
       return BadRequest(); 

      var content = _contentService.GetPublicContent(dto); 
      if (content == null) 
       return BadRequest(); 
      return new Ok(content); 

     } 

就是這樣!謝謝!!

回答

0

您可以設置它像這樣

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

更新

或者試試這個question

+0

NOP!我需要返回一個IHttpActionResul而不是一個HttpResponseMessage。謝謝! – chemitaxis 2015-03-31 22:41:31

+0

用SO鏈接更新了我的答案 – 2015-03-31 22:44:55

1

請從OkNegotiatedContentResult<T>繼承一個新的類:

public class CachedOkResult<T> : OkNegotiatedContentResult<T> 
{ 
    public CachedOkResult(T content, TimeSpan howLong, ApiController controller) : base(content, controller) 
    { 
     HowLong = howLong; 
    } 

    public CachedOkResult(T content, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) 
    : base(content, contentNegotiator, request, formatters) { } 

    public TimeSpan HowLong { get; private set; } 


    public override async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
    { 
     var response = await base.ExecuteAsync(cancellationToken); 
     response.Headers.CacheControl = new CacheControlHeaderValue() { 
      Public = false, 
      MaxAge = HowLong 
     }; 

     return response; 
    } 
} 

要使用此你的控制器,只是返回0的新實例類:

public async Task<IHttpActionResult> GetSomething(string id) 
{ 
    var value = await GetAsyncResult(id); 
    // cache result for 60 seconds 
    return new CachedOkResult<string>(value, TimeSpan.FromSeconds(60), this); 
} 

的頭會碰到電線這樣的:

Cache-Control:max-age=60 
Content-Length:551 
Content-Type:application/json; charset=utf-8 
... other headers snipped ...