开发者

Cache webservices by argument passing to the funciton

开发者 https://www.devze.com 2023-04-11 04:49 出处:网络
I wonder how can I cache webservice returned data by its passed argument? For example: [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

I wonder how can I cache webservice returned data by its passed argument?

For example:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string FunctionThatReturnsSomething(int param1){
   ... does something
return strResult;

}

What I want is that the returned the webservice returned data will be cached, but according to the parameter value (inr param1). So if, for example, the webservice function gets a value of '1', it will cache the results for that. If the functions gets '2' integer for the param1, it will cache 开发者_开发百科another result.

note: the webmethod/webservice is being called via Ajax call using POST method.


ASP.NET handily provides the Application Cache just for this sort of thing.

In it's simplest form, you can just add data to the cache like this:

HttpRuntime.Cache["Key"] = "Value"; 

So you could cache the data that you want to return easily:

string cacheKey = "FunctionThatReturnsSomething_" + param1.ToString();

if (HttpRuntime.Cache[cacheKey] == null)
{
    string myData = GetDataToReturn(param1);

    HttpRuntime.Cache[cacheKey] = myData; 
}

return (string)HttpRuntime.Cache[cacheKey];

It also allows you to specify a CacheDependancy. So for example if your data was based on a local file, you can have the cache automatically cleared if that file is updated.

You can also have data that you enter into the cache removed after a certain time, for example if it hasn't been used for 10 minutes:

HttpRuntime.Cache.Insert(cacheKey, myData, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0));

Or at an absolute time, such as 10 minutes after you add it:

HttpRuntime.Cache.Insert(cacheKey, myData, null, DateTime.Now.AddMinutes(10), 
System.Web.Caching.Cache.NoSlidingExpiration);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号