Huzefa Kagdi
Huzefa Kagdi

Reputation: 159

WCF error - Cannot receive the MessageHeaders added at the Client side

I am trying to use this simple code in WCF:

Client Side:

ServiceContractClient proxy = new ServiceContractClient();
using (OperationContextScope scope = new OperationContextScope((IContextChannel)proxy.InnerChannel))
        {
            MessageHeaders messageHeadersElement = OperationContext.Current.OutgoingMessageHeaders;
            messageHeadersElement.Add(MessageHeader.CreateHeader("username", String.Empty, System.Security.Principal.WindowsIdentity.GetCurrent().Name)); 
        }
var res = proxy.CallWCFMethod();

Server Side:

The CallWCFMethod implements another method, GetInfo(). The code for GetInfo() is :

MessageHeaders messageHeadersElement = OperationContext.Current.IncomingMessageHeaders;            
        int AdidIndex = messageHeadersElement.FindHeader("username", string.Empty);
        string ticket = messageHeadersElement.GetHeader<string>("username", string.Empty);

But this code can never find the Header "username" I added in the client. Can someone point out to me what I am doing wrong here?

Upvotes: 1

Views: 973

Answers (1)

Thorarin
Thorarin

Reputation: 48476

Your OperationContextScope is scoped too small. Put the closing brace after the proxy.CallWCFMethod() and it should work:

ServiceContractClient proxy = new ServiceContractClient();
using (OperationContextScope scope = new OperationContextScope((IContextChannel)proxy.InnerChannel))
{
    MessageHeaders messageHeadersElement = OperationContext.Current.OutgoingMessageHeaders;
    messageHeadersElement.Add(MessageHeader.CreateHeader("username", String.Empty,
        System.Security.Principal.WindowsIdentity.GetCurrent().Name)); 
    var res = proxy.CallWCFMethod();
}

You will probably have to refactor your code some more, because you will want to declare your res variable outside the using scope. You will have to explicitly type the variable in such a case.

Upvotes: 5

Related Questions