WCF消息:如何删除SOAP Header元素?

时间:2012-06-26 16:34:05

标签: c# .net wcf soap wcf-binding

我尝试从WCF消息中删除整个SOAP标头,只想离开信封体。任何人都可以告诉我该怎么做?

创建如下的WCF消息:

**string response = "Hello World!";
Message msg = Message.CreateMessage(MessageVersion.Soap11, "*", new TextBodyWriter(response));
msg.Headers.Clear();**

发送SOAP消息将是:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header />
  <s:Body>
    <Binary>Hello World!</Binary>
  </s:Body>
</s:Envelope>

但我不想要SOAP头元素,我只需要包络体。如何从WCF消息中删除头元素?

4 个答案:

答案 0 :(得分:6)

选项1:使用bacicHttpBinding,它不会向标题添加内容(未配置安全性时)

选项2:实现自定义的mesaage编码器并在那里剥离标头。在此之前的任何地方都有可能wcf会添加标题。请参阅sample encoder here

答案 1 :(得分:4)

这个问题很棘手:让我们一步一步来看待它

一些上下文

Message类将其标头写入其ToString()方法中。 ToString()然后调用内部重载ToString(XmlDictionaryWriter writer)然后开始写:

// System.ServiceModel.Channels.Message
internal void ToString(XmlDictionaryWriter writer)
{
    if (this.IsDisposed)
    {
        throw TraceUtility.ThrowHelperError(this.CreateMessageDisposedException(), this);
    }
    if (this.Version.Envelope != EnvelopeVersion.None)
    {
        this.WriteStartEnvelope(writer);
        this.WriteStartHeaders(writer);
        MessageHeaders headers = this.Headers;
        for (int i = 0; i < headers.Count; i++)
        {
            headers.WriteHeader(i, writer);
        }
        writer.WriteEndElement();
        MessageDictionary arg_60_0 = XD.MessageDictionary;
        this.WriteStartBody(writer);
    }
    this.BodyToString(writer);
    if (this.Version.Envelope != EnvelopeVersion.None)
    {
        writer.WriteEndElement();
        writer.WriteEndElement();
    }
}

无论标头数量多少,this.WriteStartHeaders(writer);代码都会写入标头标记。它在for循环后与writer.WriteEndElement()匹配。此writer.WriteEndElement() 必须与正在编写的标头标记匹配,否则Xml文档将无效。

因此我们无法覆盖虚拟方法来摆脱标题:WriteStartHeaders调用虚方法OnWriteStartHeaders但标记关闭会阻止关闭它。我们必须更改整个ToString()方法才能删除任何与标题相关的结构,以便:

- write start of envelope
- write start of body
- write body
- write end of body
- write end of envelope

解决方案

在上面的伪代码中,我们可以控制除“写入主体”部分之外的所有内容。初始ToString(XmlDictionaryWriter writer)中调用的所有方法都是公共的,BodyToString除外。所以我们需要通过反思或任何适合您需求的方法来调用它。编写没有标题的消息只会变成:

private void ProcessMessage(Message msg, XmlDictionaryWriter writer)
{
    msg.WriteStartEnvelope(writer); // start of envelope
    msg.WriteStartBody(writer); // start of body

    var bodyToStringMethod = msg.GetType()
        .GetMethod("BodyToString", BindingFlags.Instance | BindingFlags.NonPublic);
    bodyToStringMethod.Invoke(msg, new object[] {writer}); // write body

    writer.WriteEndElement(); // write end of body
    writer.WriteEndElement(); // write end of envelope
}

现在我们有了一种方法来获取没有标题的消息内容。但是如何调用这种方法呢?

我们只希望没有标题的邮件为字符串

很好,我们不需要关心覆盖ToString()方法,然后调用该消息的初始写入。只需在程序中创建一个方法,该方法需要MessageXmlDictionaryWriter并调用它来获取没有标题的邮件。

我们希望ToString()方法返回不带标题的邮件

这个有点复杂。我们不能轻易地从Message类继承,因为我们需要从System.ServiceModel程序集中提取很多依赖项。我不会在这个答案中去那里。

我们可以做的是使用某些框架的功能在现有对象周围创建proxy并拦截对原始对象的一些调用以替换/增强其行为:我习惯{ {3}}所以让我们使用它。

我们想拦截ToString()方法,因此我们围绕我们正在使用的Message对象创建一个代理,并添加一个拦截器来替换ToString的{​​{1}}方法。实现:

Message

var msg = Message.CreateMessage(MessageVersion.Soap11, "*"); msg.Headers.Clear(); var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator(); var proxiedMessage = proxyGenerator.CreateClassProxyWithTarget(msg, new ProxyGenerationOptions(), new ToStringInterceptor()); 需要与初始ToStringInterceptor方法几乎完全相同,但我们将使用上面定义的ProcessMessage方法:

ToString()

我们在这里:对消息的ToString()方法的调用现在将返回一个没有标题的信封。我们可以将消息传递给框架的其他部分并且知道它应该主要起作用:对Message的一些内部管道的直接调用仍然可以产生初始输出但是缺少完全重新实现,我们无法控制它。

注意事项

  • 这是删除我找到的标题的最短路径。编写器中的头序列化不是仅在一个虚函数中处理的事实是一个大问题。代码不会给你太多的蠕动空间。
  • 此实现不使用与public class ToStringInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { if (invocation.Method.Name != "ToString") { invocation.Proceed(); } else { var result = string.Empty; var msg = invocation.InvocationTarget as Message; StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); XmlDictionaryWriter xmlDictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(new XmlTextWriter(stringWriter)); try { ProcessMessage(msg, xmlDictionaryWriter); xmlDictionaryWriter.Flush(); result = stringWriter.ToString(); } catch (XmlException ex) { result = "ErrorMessage"; } invocation.ReturnValue = result; } } private void ProcessMessage(Message msg, XmlDictionaryWriter writer) { // same method as above } } XmlWriterToString()的原始实现中使用的Message相同的EncodingFallbackAwareXmlTextWriter。这个类在System.ServiceModel中是内部的,将它拉出来留给读者作为练习。因此,输出稍有不同,因为xml没有使用我使用的简单XmlTextWriter进行格式化。
  • 拦截器可以简单地解析从初始ToString()调用返回的xml,并在让值冒泡之前删除头节点。这是另一种可行的解决方案。

原始代码

public class ToStringInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        if (invocation.Method.Name != "ToString")
        {
            invocation.Proceed();
        }
        else
        {
            var result = string.Empty;
            var msg = invocation.InvocationTarget as Message;

            StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
            XmlDictionaryWriter xmlDictionaryWriter =
                XmlDictionaryWriter.CreateDictionaryWriter(new XmlTextWriter(stringWriter));

            try
            {
                ProcessMessage(msg, xmlDictionaryWriter);
                xmlDictionaryWriter.Flush();
                result = stringWriter.ToString();
            }
            catch (XmlException ex)
            {
                result = "ErrorMessage";
            }
            invocation.ReturnValue = result;
        }
    }

    private void ProcessMessage(Message msg, XmlDictionaryWriter writer)
    {
        msg.WriteStartEnvelope(writer);
        msg.WriteStartBody(writer);

        var bodyToStringMethod = msg.GetType()
            .GetMethod("BodyToString", BindingFlags.Instance | BindingFlags.NonPublic);
        bodyToStringMethod.Invoke(msg, new object[] { writer });

        writer.WriteEndElement();
        writer.WriteEndElement();
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        var msg = Message.CreateMessage(MessageVersion.Soap11, "*");
        msg.Headers.Clear();

        var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator();
        var proxiedMessage = proxyGenerator.CreateClassProxyWithTarget(msg, new ProxyGenerationOptions(),
            new ToStringInterceptor());

        var initialResult = msg.ToString();
        var proxiedResult = proxiedMessage.ToString();

        Console.WriteLine("Initial result");
        Console.WriteLine(initialResult);
        Console.WriteLine();
        Console.WriteLine("Proxied result");
        Console.WriteLine(proxiedResult);

        Console.ReadLine();
    }
}

答案 2 :(得分:2)

我没有你的XmlBodyWriter,但你可以使用数据合同序列化程序或你的xml正文编写器 但诀窍是使用msg.WriteBody。这将省略标题

var response = "Hello";            
Message msg = Message.CreateMessage(MessageVersion.Soap11, "*",response, new DataContractSerializer(response.GetType()));
msg.Headers.Clear();
var sb = new StringBuilder();
var xmlWriter = new XmlTextWriter(new StringWriter(sb));
msg.WriteBody(xmlWriter);

答案 3 :(得分:2)

应该是这样的:

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Body>...</Body>"

XmlNodeList xnList = xml.SelectNodes("/Envelope/Body");
foreach (XmlNode xn in xnList)
{
  string binary1 = xn["Binary1"].InnerText;
  string binary2 = xn["Binary2"].InnerText;
  Console.WriteLine("Binary: {0} {1}", binary1 , binary2);
}