我正在尝试向通过 WCF 的所有 SOAP 请求添加自定义标头。我发现这篇精彩的文章 http://blogs.msdn.com/b/mohamedg/archive/2012/10/21/adding-custom-soap-headers-in-wcf.aspx关于如何做到这一点。我的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);
}
}
这篇文章做了一件事not说的是如何read服务器上的值。根据这个帖子 https://stackoverflow.com/questions/18877591/how-to-read-http-request-headers-in-a-wcf-web-service, 您可以使用OperationContext.Current.IncomingMessageHeaders
读取这些标题。当我看到这些的时候MessageHeaders
在调试器下,我看到 3 个标头,其中包括我的自定义标头。因此,它肯定会出现在 SOAP 数据中。然而,当我打电话时GetHeader
:
OperatorNameMessageHeader test = msgHeaders.GetHeader<OperatorNameMessageHeader>(OperatorNameMessageHeader.HeaderName, OperatorNameMessageHeader.HeaderNamespace);
Then test.OperatorName
一片空白。基本上,我只是返回一个空的OperatorNameMessageHeader
尚未从 SOAP 中的数据反序列化的对象。
我的下一步是运行 WCF 跟踪工具。当我这样做时,我可以验证自定义标头是indeed通过网络发送:
<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>
那么,服务器has数据,我就是做不到get到它。这个问题的解决办法是什么?