我试图通过设置 WebMethod
属性的 CacheDuration
属性来让 ASP.Net 缓存 Web 服务请求的响应:
[WebMethod(CacheDuration = 60)]
[ScriptMethod(UseHttpGet = true)]
public static List<string> GetNames()
{
return InnerGetNames();
}
上面是 ASP.Net 页面上的一个方法(我也尝试过将其移动到自己的类中,但似乎没有任何区别) - 我设置了 UseHttpGet
为 true,因为 POST
请求没有被缓存,但是尽管我尽了最大努力,它似乎仍然没有任何区别(总是命中位于方法开头的断点)。
这是我用来调用该方法的代码:
%.ajax({
url: "MyPage.aspx/GetNames",
contentType: "application/json; charset=utf-8",
success: function() {
alert("success");
}
我是否遗漏了任何可能阻止 ASP.Net 缓存此方法的内容?
如果做不到这一点,我可以使用任何诊断机制来更清楚地了解 ASP.Net 缓存的情况吗?
最佳答案
根据这个MSDN How to article ,WebMethod 属性的 CacheDuration 属性适用于 XML WebMethod。由于 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;
}
关于asp.net - ASP.Net 缓存故障排除 - CacheDuration 属性似乎没有效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3974997/