How to: Enable Server-Side Output Caching for a Web Service
The following code example demonstrates how to use the CacheDuration property on Web service methods to specify output caching for a period of 60 seconds. This example illustrates one of the guidelines explained in the topic, Design Guidelines for XML Web Services Created Using ASP.NET.
There are two issues that can affect output caching in an ASP.NET 2.0 Web service application.
In ASP.NET 2.0 the HTTP method of the test page has changed from GET to POST. However, POSTs are not normally cached. If you change the test page in an ASP.NET 2.0 Web service application to use GET, caching works properly.
In addition, HTTP indicates that a user agent (the browser or calling application) should be able to override server caching by setting the "Cache-Control" to "no-cache". ASP.NET applications, therefore, ignore cached results when they find a "no-cache" header.
Example
<%@ WebService Language="C#" Class="MathService" %>
using System;
using System.Web.Services;
public class MathService : WebService {
[WebMethod(CacheDuration=60)]
public float Add(float a, float b)
{
return a + b;
}
[WebMethod(CacheDuration=60)]
public float Subtract(float a, float b)
{
return a - b;
}
[WebMethod(CacheDuration=60)]
public float Multiply(float a, float b)
{
return a * b;
}
[WebMethod(CacheDuration=60)]
public float Divide(float a, float b)
{
if (b==0) return -1;
return a / b;
}
}
<%@ WebService Language="VB" Class="MathService" %>
Imports System
Imports System.Web.Services
Public Class MathService
Inherits WebService
<WebMethod(CacheDuration := 60)> _
Public Function Add(a As Single, b As Single) As Single
Return a + b
End Function
<WebMethod(CacheDuration := 60)> _
Public Function Subtract(a As Single, b As Single) As Single
Return a - b
End Function
<WebMethod(CacheDuration := 60)> _
Public Function Multiply(a As Single, b As Single) As Single
Return a * b
End Function
<WebMethod(CacheDuration := 60)> _
Public Function Divide(a As Single, b As Single) As Single
If b = 0 Then
Return - 1
End If
Return a / b
End Function
End Class
See Also
Tasks
How to: Enable Output Caching on a Web Service Client
Concepts
Design Guidelines for XML Web Services Created Using ASP.NET