Output caching for an ApiController (MVC4 Web API)

后端 未结 5 1314
我在风中等你
我在风中等你 2020-12-04 23:41

I\'m trying to cache the output of an ApiController method in Web API.

Here\'s the controller code:

public class TestController : ApiController
{
            


        
5条回答
  •  星月不相逢
    2020-12-05 00:19

    I am very late, but still thought to post this great article on Caching in WebApi

    https://codewala.net/2015/05/25/outputcache-doesnt-work-with-web-api-why-a-solution/

    public class CacheWebApiAttribute : ActionFilterAttribute
    {
        public int Duration { get; set; }
    
        public override void OnActionExecuted(HttpActionExecutedContext filterContext)
        {
            filterContext.Response.Headers.CacheControl = new CacheControlHeaderValue()
            {
                MaxAge = TimeSpan.FromMinutes(Duration),
                MustRevalidate = true,
                Private = true
            };
        }
    }
    

    In the above code, we have overridden OnActionExecuted method and set the required header in the response. Now I have decorated the Web API call as

    [CacheWebApi(Duration = 20)]
            public IEnumerable Get()
            {
                return new string[] { DateTime.Now.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString() };
            }
    

提交回复
热议问题