【问题标题】:Caching of Web Service not working when request has query string当请求具有查询字符串时,Web 服务的缓存不起作用
【发布时间】:2012-09-12 04:21:29
【问题描述】:

我正在尝试实现 Web 服务调用的客户端缓存,并且根据来自 Web 的信息,我能够根据 SetCachingPolicy() 函数来实现,如图所示代码 1 如下。

我能够使用 Web 方法 RetrieveX 成功地使其工作,但不能使用方法 RetrieveY。我注意到 RetrieveX 没有参数,而 RetrieveY 有一个字符串参数,在 Fiddler 下检查,区别似乎是来自 RetrieveY 的 Web 服务调用的 HTTP GET 请求有一个参数查询字符串。

到目前为止,所有没有查询字符串的 HTTP GET Web 服务调用都在正确地进行缓存,但不是这个包含查询字符串的调用。

在Fiddler下检查发现RetrieveX在output 1有如下缓存信息,RetrieveY在output 2有缓存信息。

这是此缓存方法的限制,还是我可以做些什么来让 RetrieveY 的客户端缓存正常工作?


代码 1:SetCachingPolicy

private void SetCachingPolicy()
{
  HttpCachePolicy cache = HttpContext.Current.Response.Cache;
  cache.SetCacheability(HttpCacheability.Private);
  cache.SetExpires(DateTime.Now.AddSeconds((double)30));

  FieldInfo maxAgeField = cache.GetType().GetField(
      "_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);
  maxAgeField.SetValue(cache, new TimeSpan(0, 0, 30));
}

代码 2:RetrieveX

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public string[] RetrieveX()
{
  SetCachingPolicy();       
  // Implementation details here.
  return array;
}

代码 3:检索Y

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public string[] RetrieveY(string arg1)
{
  SetCachingPolicy();       
  // Implementation details here.
  return array;
}

输出 1:RetrieveX 缓存信息

HTTP/200 responses are cacheable by default, unless Expires, Pragma, or Cache-Control headers are present and forbid caching.
HTTP/1.0 Expires Header is present: Wed, 12 Sep 2012 03:16:50 GMT

HTTP/1.1 Cache-Control Header is present: private, max-age=30
    private: This response MUST NOT be cached by a shared cache.
    max-age: This resource will expire in .5 minutes. [30 sec]

输出 2:检索缓存信息

HTTP/200 responses are cacheable by default, unless Expires, Pragma, or Cache-Control headers are present and forbid caching.
HTTP/1.0 Expires Header is present: -1

Legacy Pragma Header is present: no-cache

HTTP/1.1 Cache-Control Header is present: no-cache
    no-cache: This response MUST NOT be reused without successful revalidation with the origin server.

【问题讨论】:

    标签: asp.net web-services caching browser-cache cache-control


    【解决方案1】:

    我也遇到了这个问题,我想我会分享对我有用的方法。根本问题是响应中没有设置 VaryByParams。如果您将此添加到您的 SetCachingPolicy() 方法中,则 RetrieveY 应该开始按预期工作:

    cache.VaryByParams["*"] = true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多