【问题标题】:Inject header into WCF outbound message将标头注入 WCF 出站消息
【发布时间】:2014-03-26 12:28:48
【问题描述】:

我有一个基于从客户提供的 WSDL 创建的类的 WCF 服务。不幸的是,这个 WSDL 没有包含所需的消息头。客户端将不会提供包含标头的新 WSDL。我确实有一个描述标题的 xsd 文件。

我还有一个示例标题,并且知道我需要填充哪些字段。

如何获取这个提供的标头 XML 并将其注入到出站 WCF 方法调用中? 我想像目前一样调用我的服务方法,但我也希望新的标头结构构成出站消息的一部分。

提前致谢。 任何和所有的帮助将不胜感激。

以下是消息结构的示例: 我需要添加整个标题结构。 WSDL 只包含正文。

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Header>
      <glob:requestHeader xmlns:glob="http://....">
         <timestamp>2013-11-14T05:17:41.793+02:00</timestamp>
         <traceMessageId>GUID</traceMessageId>
         <enterpriseTraceUUId>GUID</enterpriseTraceUUId>
         <contentType>TEXT/XML</contentType>
         <sender>
            <senderId>SENDER</senderId>
            <sourceSystem>001</sourceSystem>
            <sourceApplication>001</sourceApplication>
            <applicationSessionId>ABC</applicationSessionId>
            <sourceLocation>100</sourceLocation>
         </sender>
         <interfaceName/>
         <version>1111</version>
      </glob:requestHeader>
   </s:Header>
   <s:Body xmlns:xsi="http://.../XMLSchema-instance" xmlns:xsd="http://.../XMLSchema">
      <UserData xmlns="http://.../Base">
         <IdField>1005687</IdField>
         <UserInfo>
            <UserType>1</UserType>
            <UserStatus>Y</UserStatus>
         </UserInfo>
      </UserData>
   </s:Body>
</s:Envelope>

【问题讨论】:

  • 这就是我想要的。但在这种情况下,我在 WCF 之外定义了一个非常具体的标头结构,并且很难建模。我只想获取 XML 标头块并将其插入到消息中。

标签: c# wcf inject


【解决方案1】:

例如,我使用它来将“User-Agent”添加到我的外发消息的标题中,但我认为您可以根据自己的需要调整它:

private void AddCustomHeader(System.ServiceModel.OperationContextScope scope)
{
    dynamic reqProp = new System.ServiceModel.Channels.HttpRequestMessageProperty();
    reqProp.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT; blah; blah; blah)");
    System.ServiceModel.OperationContext.Current.OutgoingMessageProperties(System.ServiceModel.Channels.HttpRequestMessageProperty.Name) = reqProp;
}

我从我用来调用主机的客户端程序的构造函数中调用了上面的这个函数。

 AddCustomHeader(new System.ServiceModel.OperationContextScope(base.InnerChannel));

可能需要注意的最重要的事情是,它将这个标头变量添加到我的客户端使用的“当前”OperationContext 的 OutgoingMessageProperties。

【讨论】:

  • 这可能会有所帮助。你有一个更完整的例子我可以看看。我需要看看如何将它连接到我的应用程序中。
  • 其实你看到的就是我正在使用的。我只需要它来添加我添加的 User-Agent 元素。但我相信您可以推断出它以容纳您认为请求中缺少的任意数量的所需标头。
【解决方案2】:

你试过吗?也取自这里:How to add a custom HTTP header to every WCF call?

using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
{
    MessageHeader<string> header = new MessageHeader<string>("secret message");
    var untyped = header.GetUntypedHeader("Identity", "http://www.my-website.com");
    OperationContext.Current.OutgoingMessageHeaders.Add(untyped);

    // now make the WCF call within this using block
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2015-11-02
    • 2014-05-04
    相关资源
    最近更新 更多