WebMethodAttribute.CacheDuration 屬性

定義

取得或設定回應應在快取中停留的秒數。

public:
 property int CacheDuration { int get(); void set(int value); };
public int CacheDuration { get; set; }
member this.CacheDuration : int with get, set
Public Property CacheDuration As Integer

屬性值

回應應在快取中保留的秒數。 預設值為 0,表示回應未被快取。

範例

以下範例將呼叫 ServiceUsage XML Web 服務方法的結果置於快取中,持續 60 秒。 在此期間,任何 XML Web 服務用戶端執行 ServiceUsage XML Web 服務方法時,都會回傳相同的結果。

<%@ WebService Language="C#" Class="Counter" %>

using System.Web.Services;
using System;
using System.Web;

public class Counter : WebService {
     
     [ WebMethod(Description="Number of times this service has been accessed",
     CacheDuration=60,MessageName="ServiceUsage") ]
     public int ServiceUsage() {
          // If the XML Web service has not been accessed, initialize it to 1.
          if (Application["MyServiceUsage"] == null) {
              Application["MyServiceUsage"] = 1;
          }
          else {
              // Increment the usage count.
              Application["MyServiceUsage"] = ((int) Application["MyServiceUsage"]) + 1;
          }

          // Return the usage count.     
          return  (int) Application["MyServiceUsage"];
     }
}
<%@ WebService Language="VB" Class="Counter" %>

Imports System.Web.Services
Imports System
Imports System.Web

Public Class Counter
    Inherits WebService  

    <WebMethod(Description := "Number of times this service has been accessed", _
        CacheDuration := 60, _
        MessageName := "ServiceUsage")> _
    Public Function ServiceUsage() As Integer
        
        ' If the XML Web service has not been accessed, initialize it to 1.
        If Application("MyServiceUsage") Is Nothing Then
            Application("MyServiceUsage") = 1
        Else
            ' Increment the usage count.
            Application("MyServiceUsage") = CInt(Application("MyServiceUsage")) + 1
        End If
        
        ' Return the usage count.
        Return CInt(Application("MyServiceUsage"))
    End Function
End Class

備註

啟用快取時,請求與回應會在伺服器的記憶體中保存至少快取期間,因此若預期請求或回應會非常龐大或請求變化很大,則需謹慎。

在 ASP.NET 2.0 Web 服務應用程式中,有兩個問題可能會影響輸出快取。

在 ASP.NET 2.0 中,測試頁面的 HTTP 方法由 GET 改為 POST。 然而,POST 通常不會被快取。 如果你在 ASP.NET 2.0 Web 服務應用程式中更改測試頁面以使用 GET,快取功能會正常運作。

此外,HTTP 表示使用者代理(瀏覽器或呼叫應用程式)應能透過將「快取控制」設為「無快取」來覆寫伺服器快取。 因此,ASP.NET 應用程式在找到「無快取」標頭時會忽略快取結果。

適用於