Sometimes you may require, that every message you send in context of calling of an operation, has some custom header. This should not be a big problem by implementing of messages on the messaging layer. However you may want to stay on the operation level (high-level) and manipulate the header of the message. The easiest way to do that is shown in the following example:
MessageHeader sessionKeyHeader = MessageHeader.CreateHeader("SessionKey", "http://daenet.eu/SessionSharing", "Game1");
OperationContext.Current.OutgoingMessageHeaders.Add(sessionKeyHeader);
chn1.DoSomething();
This example shows how to append an additional header to the message which will be sent when the client invokes the operation DoSomething().
After the operation is invoked following message is sent.
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:r="http://schemas.xmlsoap.org/ws/2005/02/rm" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<r:Sequence s:mustUnderstand="1">
<r:Identifier>urn:uuid:294dfca8-11e6-41d7-acdd-79250f026a8d</r:Identifier>
<r:MessageNumber>1</r:MessageNumber>
</r:Sequence>
<a:Action s:mustUnderstand="1">http://tempuri.org/IHello/DoSomething</a:Action>
<SessionKey xmlns="http://daenet.eu/SessionSharing">Game1</SessionKey>
<a:MessageID>urn:uuid:a44f8afc-191d-4a39-bfcd-f1724c87169f</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand="1">http://localhost:7777/helloService/helloEndpoint</a:To>
</s:Header>
<s:Body>
<DoSomething xmlns="http://tempuri.org/"></DoSomething>
</s:Body>
</s:Envelope>
Unfortinately this example will not work, because the OperationContext.Current is NULL reference. To avoid this problem following code can be used:
ChannelFactory<HelloService.IHello> cnFactory = new ChannelFactory<HelloService.IHello>("helloClient");
HelloService.IHello chn1 = cnFactory.CreateChannel();
using (new OperationContextScope((IContextChannel)chn1))
{
MessageHeader sessionKeyHeader = MessageHeader.CreateHeader("SessionKey", "http://daenet.eu/SessionSharing", "Game1");
OperationContext.Current.OutgoingMessageHeaders.Add(sessionKeyHeader);
chn1.DoSomething();
}
This code creates the temporary OperationContext, which allows us to set the property OutgoingMessageHeaders. This is not nice solution, but it helps. Please note, that all calls to all operations whithin the scope defined by “using” will append the custom header with the name “SessionKey”.
On the service side, the header can be found as shown:
OperationContext.Current.RequestContext.RequestMessage.Headers.FindHeader(“SessionKey”, “http://daenet.eu/SessionSharing”)
Posted
Oct 20 2006, 10:57 PM
by
Damir Dobric