Web API 2.0 IHttpActionResult缓存

时间:2015-03-31 15:41:13

标签: c# caching asp.net-web-api asp.net-mvc-5

我使用此代码返回对象内容,但我想缓存添加Cache-Control标题的响应。

[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);

        }

就是这样!谢谢!

2 个答案:

答案 0 :(得分: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;
    }
}

要在控制器中使用它,只需返回CachedOkResult类的新实例:

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 ...

答案 1 :(得分: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