在内存中缓存WebClient请求

时间:2016-07-18 22:45:02

标签: webclient-download

我有以下要求:

            WebClient client = new WebClient();
        client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
        var data = client.DownloadString("http://finance.yahoo.com/webservice/v1/symbols/IBM,%5EIXIC/quote?format=json&view=detail");

        StringBuilder builder = new StringBuilder();
        builder.Append("<script type=\"text/javascript\">");
        builder.Append("stockQuotes = new Object();");
        builder.Append(data);
        builder.Append("</script>");

        ltrData.Text = builder.ToString();

有没有办法可以将响应缓存在内存中30分钟?如果是这样怎么样?

1 个答案:

答案 0 :(得分:0)

能够使用以下功能让它工作......希望它能在某个时间点帮助其他人。

这样称呼:

var jsonObject1 = JsonConvert.DeserializeObject<Rootobject>(GetCachedJson(true, 120));

使用以下方法:

 public static string GetCachedJson(bool requireCache, int minuteInCache)
    {
        if (requireCache)
        {
            if (HttpRuntime.Cache[CacheKey()] == null)
            {
                string dataJSON = GetJSONPeopleDetails();
                HttpRuntime.Cache.Insert(CacheKey(), dataJSON, null, DateTime.Now.AddMinutes(minuteInCache), Cache.NoSlidingExpiration);
            }

            return HttpRuntime.Cache[CacheKey()].ToString();
        }
        else
        {
            return GetJSONPeopleDetails();
        }
    }

    private static string CacheKey()
    {
        string CACHE_NAME = "JSON_Blah.RESPONSE" + HttpContext.Current.Request.QueryString["uid"];
        return CACHE_NAME;
    }