Jus*_*tin 5 asp.net ajax jquery caching
我试图通过设置CacheDuration
属性的WebMethod
属性让ASP.Net缓存Web服务请求的响应:
[WebMethod(CacheDuration = 60)]
[ScriptMethod(UseHttpGet = true)]
public static List<string> GetNames()
{
return InnerGetNames();
}
Run Code Online (Sandbox Code Playgroud)
以上是ASP.Net页面上的一个方法(我也尝试将它移动到自己的类,但它似乎没有任何区别) - 我设置UseHttpGet
为true因为POST
请求没有缓存,但是尽管我付出了最大的努力,它似乎仍然没有任何区别(方法开始处的断点总是被击中).
这是我用来调用方法的代码:
%.ajax({
url: "MyPage.aspx/GetNames",
contentType: "application/json; charset=utf-8",
success: function() {
alert("success");
}
Run Code Online (Sandbox Code Playgroud)
有什么我错过了可能阻止ASP.Net缓存此方法的东西吗?
如果不这样做,我是否可以使用任何诊断机制来更清楚地了解ASP.Net缓存的情况?
根据MSDN How to article,WebMethod属性的CacheDuration属性适用于XML WebMethods.由于ScriptMethod属性指定返回JSON,因此我们不得不使用对象级缓存:
[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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
862 次 |
最近记录: |