SoapHeaders can be used to send “extra” and optional parameters to web service methods and is a technique which can be extremely useful. See the following example:
Server-side (MyService.asmx):
public class MyService : System.Web.Services.WebService { public class AddDateHeader : SoapHeader { public bool AddDate; } public AddDateHeader myheader; ... [WebMethod] [SoapHeader("myheader")] public string HelloWorld() { if (myheader != null && myheader.AddDate == true) return "Hello World " + DateTime.Now.ToString(); else return "Hello World"; }
Client-side:
localhost.MyService si = new localhost.MyService(); si.AddDateHeaderValue = new localhost.AddDateHeader(); si.AddDateHeaderValue.AddDate = true; MessageBox.Show(si.HelloWorld());
Furthermore, these headers can be accessed in SoapExtension components. For example, there might be a SoapHeader that controls the transport of data.
Example:
Public Overrides Sub ProcessMessage(ByVal message As SoapMessage) Dim compress As Boolean = False Dim header As SoapHeader For Each header In message.Headers If header.GetType().Name = "Compress" Then compress = True End If Next ...
Sometimes it’s useful to have the header sent in both directions (both to and from the service). In this case, apply the attribute to the web method with the Direction attribute:
[SoapHeader("myheader", Direction = SoapHeaderDirection.InOut)] public string HelloWorld() { ...