Barış Kısır

Senior Software Developer

Navigation
 » Home
 » RSS

Caching in Web API 2

28 May 2017 » csharp

What is caching?

People with same interest, calls your API over and over again and your server runs every request even if the response is same.

At server side, its not efficient at all.

In this scenerio, we should save our response and send same response to users for X time.

What if my response is changed?

Don’t worry! We will run request every X time.

Let’s get started!

We will use Strathweb.CacheOutput.WebApi2

Installation with NuGet

Install-Package Strathweb.CacheOutput.WebApi2

Let’s create an api for getting random string.

Response class

public class Response
{
    public string RandomString { get; set; }
    public string CacheDate { get; set; }
}

Default Controller

public class DefaultController : ApiController
{
    [Route("api/Get/")]
    //Cache time is 60 seconds.
    [CacheOutput(ServerTimeSpan = 60)]
    public Response GetRandomString()
    {
        var response = new Response();
        response.RandomString = Guid.NewGuid().ToString().Replace("-", "");
        response.CacheDate = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss");
        return response;
    }
}

You can download source code from –> Here