是否可以在ActionFilterAttribute中设置Web Api响应的到期时间?

时间:2015-02-21 20:10:34

标签: asp.net asp.net-web-api

我想为我的一些Web Api响应设置过期,以鼓励缓存非常不频繁变化的数据。为此,我创建了一个ActionFilterAttribute:

public class ClientCacheFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnActionExecuted(actionExecutedContext);
        var expiry = DateTime.UtcNow.Date.AddMonths(1).ToString("R");
        actionExecutedContext.Response.Content.Headers.Add("Expires", expiry);
    }
}

......我也试过这个:

public class ClientCacheFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnActionExecuted(actionExecutedContext);
        actionExecutedContext.Response.Content.Headers.Expires = DateTime.UtcNow.Date.AddMonths(1);
    }
}

...并将其适当地附加到控制器方法:

public class MyDataController : ApiController
{
    [HttpGet]
    [ClientCacheFilter]
    public List<MyObject> GetMyData()
    {
         return /* the data I want to return */
    }
}

当我检查响应时,我看到Expires标头的值为-1。似乎我无法在响应标头上设置我想要的到期日。我在调试下运行,所以我知道正在执行动作过滤器方法。我忽视或做错了什么?

1 个答案:

答案 0 :(得分:4)

您还需要设置CacheControl标头:

[HttpGet]
public IHttpActionResult GetMyData()
{
    var response = Request.CreateResponse(HttpStatusCode.OK, myData);
    response.Content.Headers.Expires = DateTime.UtcNow.Date.AddMonths(1);
    // without this the Expires header won't be set!
    response.Headers.CacheControl = new CacheControlHeaderValue();
    return ResponseMessage(response);
}

或者,您可以在CacheControl中设置max-age指令,而不是设置Expires标头:

[HttpGet]
public IHttpActionResult GetMyData()
{
    var response = Request.CreateResponse(HttpStatusCode.OK, myData);
    response.Headers.CacheControl = new CacheControlHeaderValue
    {
        Public = true,
        MaxAge = TimeSpan.FromDays(30)
    };

    return ResponseMessage(response);
}