There are a number of reasons you may want to add custom headers to a SOAP message:
Luckily adding custom Soap headers is easy in the .NET framework.
Part 1: Adding SOAP headers to a webservice
After creating your basic webservice.
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Service1 : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello, world!"; } }
And defining your soapheader; any xml serializable class, deriving from SoapHeader.
[XmlRoot("userNamePasswordHeader")] public class UserNamePasswordHeader : SoapHeader { public UserNamePasswordHeader() : base() { } [XmlElement("userName")] public string UserName;
[XmlElement("password")] public string Password;
}
Hooking everything up is straightforward. One way is to add a field or property to the webservice class to hold the soapheaders and add the soapheader attribute to the method to associate the headers to it. Adding the unknownheaders fields allows the method to intercept the undefined headers. This results in the following class:
public class Service1 : System.Web.Services.WebService { [WebMethod] [SoapHeader("UserNamePasswordHeader")] public string HelloWorld() { string userName = this.UserNamePasswordHeader.UserName; return "Hello, " + userName; } public UserNamePasswordHeader UserNamePasswordHeader; public SoapHeader[] UnknownHeaders; }
Offcourse you can use the value of the headers in the method call, but usually you want to process the headers in a soap extension.
A soapextension, a class deriving from the SoapExtension class, can also be used to add headers to response messages, by adding them in the ProcessMessage method during the BeforeSerialize stage.
public class TimeStampExtension : SoapExtension{ public TimeStampExtension() :base(){} public override object GetInitializer(Type serviceType) { return null; } public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return null; } public override void Initialize(object initializer) { // do nothing } public override void ProcessMessage(SoapMessage message) { switch( message.Stage ){ case SoapMessageStage.BeforeSerialize: AddTimeStamp(message); break; default: // do nothing break; } } private void AddTimeStamp(SoapMessage message) { message.Headers.Add(new TimeStampHeader()); } }
Seting up the soap extension is done in the web.config file.
<configuration> <system.web> <webServices> <soapExtensionTypes> <add type="WebService.TimeStampExtension, WebService" group="High" priority="2"/> </soapExtensionTypes> </webServices> </system.web> </configuration>
Source: WebService.zip (4.63 KB)