burntmarshmallows
burntmarshmallows

Reputation: 168

Cache database results in WebAPI authentication

I am creating a RESTful web service using ASP.NET WebApi. I am requiring that all incoming requests go over SSL because I will be using Basic HTTP Authentication. The client is responsible for including the credentials in the request header and the web service will authenticate the client on each request.

The actual authentication requires making a database call. Is there a way to cache the database results (the username and password) so that I don't have to make a database call for every incoming request that occurs in a short period of time?

So when a request comes in the web service will look for the username/password combo in the cache. If it is found it will process the request. If it isn't found, it will make the database call to authenticate and then add the username/password to the cache.

Upvotes: 0

Views: 456

Answers (1)

Mike Stonis
Mike Stonis

Reputation: 2188

The easiest cache that I can think of to use would be using System.Web.Caching. Below is an extremely simplified version of adding a value to the current cache and then retrieving it for processing. I would not recommend using this code as is.

// GET api/values/5
[HttpGet]
public string GetValue(int id)
{
    HttpContext.Current.Cache.Insert("2", "test1");

    var value = Convert.ToString(HttpContext.Current.Cache.Get(id.ToString()));

    return !string.IsNullOrEmpty(value) ? value : "nothing found";
}

Upvotes: 2

Related Questions