【发布时间】:2014-08-19 17:10:48
【问题描述】:
我正在尝试通过 WCF 向所有 SOAP 请求添加自定义标头。我找到了this fantastic article,了解如何做到这一点。我的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);
}
}
文章没有说的一件事是如何读取服务器上的值。根据this post,您可以使用OperationContext.Current.IncomingMessageHeaders 来读取这些标头。当我在调试器下查看这些MessageHeaders 时,我看到了 3 个标题,包括我的自定义标题。因此,它肯定会出现在 SOAP 数据中。但是,当我打电话给GetHeader:
OperatorNameMessageHeader test = msgHeaders.GetHeader<OperatorNameMessageHeader>(OperatorNameMessageHeader.HeaderName, OperatorNameMessageHeader.HeaderNamespace);
那么test.OperatorName 为空。基本上,我只是取回一个尚未从 SOAP 中的数据反序列化的空 OperatorNameMessageHeader 对象。
我的下一步是运行 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>
所以,服务器有数据,我只是无法获取它。有什么办法解决这个问题?
【问题讨论】:
-
我现在遇到了这个问题,您找到解决方案了吗?
-
@Declan - 从来没有!不过,我最终找到了一种使用 HTTP 标头做同样事情的方法。该信息不在 SOAP 中,仅适用于 HTTP,因此对某些人来说可能会破坏交易。
-
@MikeChristensen 我遇到了同样的问题。你应该在这个问题上悬赏:)