0

I'm not sure of the best way to approach this, but here is my scenario.

Let's say I have an ashx handler that feeds out some data to an ajax request from the client. Something simple like:

public class Handler : IHttpHandler
{
    private List<MyObject> data;

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        data = GetData();
        string result;

        switch (context.Request.QueryString["requestType"])
        {
            case "case":
                result = Foo.Bar(data).GetJSON();
                break;

            // .. several more data conversitions / comparisions 
        }

        context.Response.Write(result);
    }

    public class MyObject
    {
        public int Id { get; set; }
        public string Data { get; set; }
    }
}

How would I cache the list of MyObject's so it is not rebuilt every time a request is made to the service? Let's say the list of MyObject gets thousands of results and I want to keep it cached for ~1 minute. Could I make use of context.Cache?

Basically; I do not want to cache the handlers output. Just an object with data that resides in it.

Edit: I am looking for something along the lines of:

data = (List<MyObject>) context.Cache["data"];

if (data == null || !data.Any())
{
    data = GetData();
    context.Cache.Insert("data", data, null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration);
}
mikeds
  • 187
  • 3
  • 11

1 Answers1

1

You can add result to HttpContext.Current.Cache, something like this :

var requestType = context.Request.QueryString["requestType"];
HttpContext.Current.Cache[requestType] = result;
Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102