我正在尝试在WCF的所有SOAP请求中添加自定义标头。 我在这篇精彩的文章中找到了如何实现此操作的方法。 我的MessageHeader
类如下所示:
public class OperatorNameMessageHeader : MessageHeader
{
private string opName;
public const string HeaderName = "OperatorNameMessageHeader";
public const string HeaderNamespace = "http://schemas.microsoft.com/scout";
public override string Name { get { return HeaderName; } }
public override string Namespace { get { return HeaderNamespace; } }
public string OperatorName
{
get { return opName; }
set { opName = value; }
}
public OperatorNameMessageHeader()
{
}
public OperatorNameMessageHeader(string operatorName)
{
opName = operatorName;
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteElementString("OperatorName", opName);
}
}
这篇文章没有提到如何从服务器上读取值。根据这篇文章,您可以使用OperationContext.Current.IncomingMessageHeaders
来读取这些标头。当我在调试器下查看这些MessageHeaders
时,我看到了包括我的自定义标头在内的3个标头。因此,它绝对显示在SOAP数据中。但是,当我调用GetHeader
时:
OperatorNameMessageHeader test = msgHeaders.GetHeader<OperatorNameMessageHeader>(OperatorNameMessageHeader.HeaderName, OperatorNameMessageHeader.HeaderNamespace);
然后
test.OperatorName
是空的。基本上,我只是得到了一个空的OperatorNameMessageHeader
对象,它没有从SOAP中的数据反序列化。我的下一步是运行WCF跟踪工具。当我这样做时,我可以验证自定义标头确实正在通过网络发送:
<MessageHeaders>
<ActivityId CorrelationId="66a7c5b6-3548-4f3c-9120-4484af76b64b" xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics">f9bef03b-4e7b-4e84-b327-5e79814d9933</ActivityId>
<OperatorNameMessageHeader xmlns="http://schemas.microsoft.com/scout">
<OperatorName>Correct Operator Name</OperatorName>
</OperatorNameMessageHeader>
<To d4p1:mustUnderstand="1" xmlns:d4p1="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://localhost:90/IRolesAndResourcesManager</To>
<Action d4p1:mustUnderstand="1" xmlns:d4p1="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IRolesAndResourcesManager/Authenticate</Action>
</MessageHeaders>
所以,服务器上有数据,只是我无法获取它。这个问题的解决方案是什么?