Cache an object in a .ashx handler

时光毁灭记忆、已成空白 提交于 2019-12-13 08:25:18

问题


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);
}

回答1:


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

var requestType = context.Request.QueryString["requestType"];
HttpContext.Current.Cache[requestType] = result;


来源:https://stackoverflow.com/questions/14297580/cache-an-object-in-a-ashx-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!