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.
精彩评论