0

I have standard WebAPI methods like this. The methods use Entity Framework 6.1 to retrieve data from a SQL Server 2012 database:

    [ResponseType(typeof(Content))]
    public async Task<IHttpActionResult> Get(int id)
    {
        Content content = await db.Contents.FindAsync(id);
        if (content == null)
        {
            return NotFound();
        }

        return Ok(content);
    }

Is there a way that the response could be cached so it does not access the database every time?

  • you can use the .net caching , i am not sure why you are so doubtful ? – Devesh Jun 09 '14 at 12:50
  • I am not doubtful. It's just I have no idea how to do it. Sorry maybe my question was not worded so good. –  Jun 09 '14 at 13:06
  • If you're on Azure use the redis cache and the sample code from http://azure.microsoft.com/blog/2014/06/05/mvc-movie-app-with-azure-redis-cache-in-15-minutes/ – RickAndMSFT Jun 13 '14 at 17:55

2 Answers2

1

I think you might need to make use of ETags (Entity Tags). I haven't tried this myself, but this or that blog articles might be useful to you. The latter also includes lots of other links to blog articles about caching.

djikay
  • 10,450
  • 8
  • 41
  • 52
0

You can use like this

     if(HttpContext.Current.Cache["myKey"] == null){
             //Get the data from the database;  
               HttpContext.Current.Cache["myKey"] = content;
     }else
        return ok((Content)HttpContext.Current.Cache["myKey"]);

As your content can be null , keep one more cache item to track if content is there but null

        HttpContext.Current.Cache["IsData"] = content == null ? false : true;

Now do like this

            if(HttpContext.Current.Cache["IsData"] == null){
             //Get the data from the database; 
              HttpContext.Current.Cache["IsData"] = content == null ? false : true; 
              if(content != null){
               HttpContext.Current.Cache["myKey"] = content;

            }
     }  else
        return HttpContext.Current.Cache["myKey"] != null ? ok((Content)HttpContext.Current.Cache["myKey"]) : NotFound();;

This logic is apply to any kind of caching you are going to use.

Devesh
  • 4,500
  • 1
  • 17
  • 28
  • To make it easy to follow can you show me how this could fit in with the controller method example in my question. Thanks. –  Jun 09 '14 at 15:36
  • @devesh: so, assuming I understand this correctly, what happens if the content changes in the database *after* you cache it? I think you will always get the originally cached content and therefore you'll miss any changes made to it. I'm not sure how your example is able to cope with this case. Perhaps I'm wrong, it'd be nice if you could explain. – djikay Jun 09 '14 at 21:39