【问题标题】:Caching an HTTP_POST jQuery Ajax Request Result with C# WebMethod使用 C# WebMethod 缓存 HTTP_POST jQuery Ajax 请求结果
【发布时间】:2012-12-07 18:19:51
【问题描述】:

这是我想不通的事情。

我有大型 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);

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

谢谢!

【问题讨论】:

    标签: c# web-services jquery http-caching


    【解决方案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 调用您的网络服务:

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

    【讨论】:

      【解决方案2】:

      WebMethod 属性上有一个属性,您可以设置缓存。我不确定这是否会在标头中设置缓存值。

      http://msdn.microsoft.com/en-us/library/byxd99hx%28v=vs.71%29.aspx#vbtskusingwebmethodattributecacheduration

      【讨论】:

      • 谢谢,我应该补充一点,我已经在 WebMethod 上尝试了 CacheDuration,但没有成功。
      • HttpContext.Current.Response.End();在你的方法结束之前返回?
      猜你喜欢
      • 1970-01-01
      • 2015-01-12
      • 2011-05-22
      • 2015-01-06
      • 2016-10-05
      • 2010-10-13
      • 2018-01-09
      • 1970-01-01
      相关资源
      最近更新 更多