gpt4 book ai didi

c# - 使用 C# WebMethod 缓存 HTTP_POST jQuery Ajax 请求结果

转载 作者:太空宇宙 更新时间:2023-11-03 13:50:46 25 4
gpt4 key购买 nike

这是我想不通的事情。

我有一个大型 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 header 总是如下所示:

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);

Web 服务不适用于 HTTP GET,对吧?或者我应该怎么做?

谢谢!

最佳答案

为了最大限度地控制,您可以像这样设置缓存响应 header :

    <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 调用您的网络服务:

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);
}
});

关于c# - 使用 C# WebMethod 缓存 HTTP_POST jQuery Ajax 请求结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13768787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com