开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜