Implement Custom SOAP Headers
The sample authentication service contains one publicly accessible method, Authenticate, which requires an encrypted username and password combination to be passed in a custom SOAP header. To define a bit of custom data to be passed in the header of a SOAP call, first define a class to encapsulate the data:
public class TokenHeader : SoapHeader
{
//holds a base64 encoded string with encrypted username and
//password information
public String Token;
}
To use the header in a public Web service method, declare a public member variable of the header type (TokenHeader in this case.) Next, decorate the public Web service method with an attribute referencing the header class:
public class AuthSvc : WebService
{
public TokenHeader AuthToken;
[WebMethod]
[SoapHeader("AuthToken", Direction=SoapHeaderDirection.In, Required=true)]
public String Authenticate()
{
//Code to authenticate a user using the AuthToken object...
}
}
The SoapHeader attribute references the AuthToken member variable and specifies that the header is a required input-only header. ASP.NET takes care of all of the SOAP plumbing from this point forward.
Implementing custom SOAP headers from the client side is equally easy:
AuthSvc authServer = new AuthSvc();
TokenHeader header = new TokenHeader();
//Code to populate the TokenHeader object with an encrypted
//username and password pair...
authServer.TokenHeaderValue = header;
bool isAuthenticated = authServer.Authenticate();
Be sure to define the custom header object (TokenHeader) separately and then assign the header to the Web service proxy object (authServer) in a second step, as the code excerpt does.