Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output caching for an ApiController (MVC4 Web API)

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

Here's the controller code:

public class TestController : ApiController {     [OutputCache(Duration = 10, VaryByParam = "none", Location = OutputCacheLocation.Any)]     public string Get()     {         return System.DateTime.Now.ToString();     } } 

N.B. I'd also tried the OutputCache attribute on the controller itself, as well as several combinations of its parameters.

The route is registered in Global.asax:

namespace WebApiTest {     public class Global : HttpApplication     {         protected void Application_Start(object sender, EventArgs e)         {             RouteTable.Routes.MapHttpRoute("default", routeTemplate: "{controller}");         }     } } 

I get a successful response, but it's not cached anywhere:

HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Content-Type: application/xml; charset=utf-8 Expires: -1 Server: Microsoft-IIS/7.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Wed, 18 Jul 2012 17:56:17 GMT Content-Length: 96  <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">18/07/2012 18:56:17</string> 

I was not able to find documentation for output caching in Web API.

Is this a limitation of the Web API in MVC4 or am I doing something wrong?

like image 660
Samu Lang Avatar asked Jul 18 '12 18:07

Samu Lang


People also ask

Is caching possible in web API?

Caching is very common to make applications performant and scalable. If a result is already computed by the application, it is cached in a store so that next time when the same request comes, cached result can be fetched instead of processing the request again.

What is output caching?

The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked. Imagine, for example, that your ASP.NET MVC application displays a list of database records in a view named Index.


1 Answers

WebAPI does not have any built in support for the [OutputCache] attribute. Take a look at this article to see how you could implement this feature yourself.

like image 75
Cory Avatar answered Sep 25 '22 13:09

Cory