这是我无法弄清楚的事情。
我有大量的JSON数据集,我希望客户端在浏览器中缓存。 我正在使用jquery AJAX来调用c#web方法。
[System.Web.Services.WebMethod]
这是jQuery:
$.ajax({
url: "/Ajax/ItemAffinity.aspx/FetchAffinityItems?ItemID=" + escape($("#SearchSelectedPageID").val()),
type: "POST",
data: "{}",
cache: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
//contentType: "application/json; charset=utf-8",
success: function (data) {
//do cool stuff
}
});
无论我在Web方法中的服务器上指定什么,HTTP HEADERS总是会回来看起来像这样:
Cache-Control no-cache
Content-Length 919527
Content-Type application/json; charset=utf-8
Expires -1
我立即忽略了我放入网络服务的任何设置,如下所示:
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(1));
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
Webservices不能与HTTP GET一起使用,对吗? 或者我该怎么做?
谢谢!
答案 0 :(得分:1)
为了获得最大程度的控制,您可以设置缓存响应标头,如下所示:
<WebMethod()> _
<ScriptMethod(UseHttpGet:=True)> _
Public Function get_time() As String
'Cache the reponse to the client for 60 seconds:
Dim context As HttpContext = HttpContext.Current
Dim cacheExpires As New TimeSpan(0, 0, 0, 60)
SetResponseHeaders(context, HttpCacheability.Public, cacheExpires)
Return Date.Now.ToString
End Function
''' <summary>
''' Sets the headers of the current http context response.
''' </summary>
''' <param name="context">A reference to the current context.</param>
''' <param name="cacheability">The cachability setting for the output.</param>
''' <param name="delta">The amount of time to cache the output. Set to Nothing if NoCache.</param>
''' <remarks></remarks>
Public Shared Sub SetResponseHeaders(ByRef context As HttpContext,
cacheability As HttpCacheability,
delta As TimeSpan)
If Not IsNothing(context) Then
Dim cache As HttpCachePolicy = context.ApplicationInstance.Response.Cache
cache.SetCacheability(cacheability)
Select Case cacheability
Case HttpCacheability.NoCache
'prevent caching:
Exit Select
Case Else
'set cache expiry:
Dim dateExpires As Date = Date.UtcNow
dateExpires = dateExpires.AddMinutes(delta.TotalMinutes)
'set expiry date:
cache.SetExpires(dateExpires)
Dim maxAgeField As Reflection.FieldInfo = cache.GetType.GetField("_maxAge", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
If Not IsNothing(maxAgeField) Then
maxAgeField.SetValue(cache, delta)
End If
End Select
End If
End Sub
然后使用ajax GET调用您的web服务:
var postObj = {
ItemID: 12
}
$.ajax({
url: webserviceUrl,
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: postObj,
success: function (reponse) {
alert(response.d);
}
});
答案 1 :(得分:0)
WebMethod属性上有一个属性,您可以设置缓存。我不确定这是否在标题中设置了缓存值。