asp.net - ASP.Net 缓存故障排除 - CacheDuration 属性似乎没有效果

标签 asp.net jquery ajax caching

我试图通过设置 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/

相关文章:

javascript - 需要 DIV 的客户端拼写检查器

asp.net - gridview 标题中的下拉列表和 rowdatabound 列更改

c# - 存储过程在 SSMS 中运行良好,但在 C# 中调用时没有返回任何行

javascript - 带有内圆的 Jquery 饼图

jQuery AJAX POST 请求在 ie9 中丢弃正文

c# - XmlReader.Create() 远程服务器返回错误 : (403) Forbidden

javascript - jQuery .attr (“disabled”, “disabled”)在 IE 10 中不起作用

javascript - 在容器中仅显示 8 行文本

javascript - ajax 与 php 的连接在子目录中不起作用

javascript - 显示 JSON 响应