Troubleshooting ASP.Net caching - CacheDuration property seems to have no effect
I'm trying to get ASP.Net to cache the response of a web service request by setting the开发者_如何学Go CacheDuration
property of the WebMethod
attribute:
[WebMethod(CacheDuration = 60)]
[ScriptMethod(UseHttpGet = true)]
public static List<string> GetNames()
{
return InnerGetNames();
}
The above is a method on an ASP.Net page (I've also tried moving it to its own class, but it didn't seem to make any difference) - I've set UseHttpGet
to true because POST
requests aren't cached, however despite my best efforts it still doesn't seem to be making any difference (a breakpoint placed at the start of the method is always hit).
This is the code I'm using to call the method:
%.ajax({
url: "MyPage.aspx/GetNames",
contentType: "application/json; charset=utf-8",
success: function() {
alert("success");
}
Is there anything that I've missed which might be preventing ASP.Net from caching this method?
Failing that, are there any diagnostic mechanisms I can use to more clearly understand what's going on with the ASP.Net caching?
According to this MSDN How to article, the CacheDuration property of the WebMethod attribute is for XML WebMethods. Since the ScriptMethod attribute specifies to return JSON, we're forced to use object level caching instead:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<string> GetNames()
{
var result = GetCache<List<string>>("GetNames");
if(result == null)
{
result = InnerGetNames();
SetCache("GetNames", result, 60);
}
return result;
}
protected static void SetCache<T>(string key, T obj, double duration)
{
HttpContext.Current.Cache.Insert(key, obj, null, DateTime.Now.AddSeconds(duration), System.Web.Caching.Cache.NoSlidingExpiration);
}
protected static T GetCache<T>(string key) where T : class
{
return HttpContext.Current.Cache.Get(key) as T;
}
Verify that your browser is not sending a Cache-control: no-cache header with its request. According to the documentation, cached results are not sent if the user agent has specified no-cache.
Based on the .ajax call you posted, you should be good, but double checking what is actually sent to the server will let you be sure.
A tool like fiddler is invaluable for debugging exactly what is going on over the wire for browser/web service interaction.
精彩评论