Jeff
Jeff

Reputation:

WCF OutgoingMessageHeaders not saving values

I am trying to write a MessageHeader to the OutgoingMessageHeaders but the value isn't sticking.

BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
EndpointAddress endpointAddress = new EndpointAddress("http://localhost:1003/Client.svc");

IClientService serviceClient = new ChannelFactory<IClientService>(basicHttpBinding, endpointAddress).CreateChannel();

// attempt 1
using (OperationContextScope scope = new OperationContextScope(serviceClient as IContextChannel)) 
{
    OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("SessionId","","ABC"));
}

// attempt 2
using (OperationContextScope scope = new OperationContextScope(serviceClient as IContextChannel)) 
{
    OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("SessionId","","ABC"));
}

OK, you can see that I am setting OutgoingMessageHeaders twice but that is simply to prove a point. In the second attempt, before I do the actual add, I inspect the OperationContext.Current.OutgoingMessageHeaders. I would expect this to have one entry. But it is zero. As soon as it gets out of the using scope the value is lost.

When this flows through to the server, it says it can't find the message header, indicating that as far as its concerned it hasn't been saved either.

Why isn't my MessageHeader sticking?

Jeff

Upvotes: 2

Views: 2177

Answers (1)

Maurice
Maurice

Reputation: 27632

The end of the using block calls the dispose and resets the previous OperationContext.

So you want something like this with the service call inside of the OperationContextScope.

        using (OperationContextScope scope = new OperationContextScope(serviceClient as IContextChannel))
        {
            OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("SessionId", "", "ABC"));
            serviceClient.CallOperation();
        }

Upvotes: 8

Related Questions