C# WCF - 创建自定义消息内容

标签 c# xml wcf

我一直在使用可用的 IClientMessageInspector(和 IDispatchMessageInspector)检查在基于 WCF 的系统中发送的消息。

目前我正在尝试手动将 XML 添加到消息中,但我无法让它工作。

情况: 传入消息的正文如下

<s:Body>
    <Type xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
    ...
    </Type>
</s:Body>

我想用自定义内容替换整个正文,在字符串中手动构建。即,我在字符串中有一个正确的 XML 正文,我想将其放在消息正文中。

这可能吗?

编辑: 为了进一步澄清这个问题:我能否以某种方式访问​​消息的“原始文本”并进行编辑?

Edit2:即我想保留原始 header 和传入消息中的所有内容,但想替换

之间的所有内容
<body> </body> 

我的自定义内容目前位于一个字符串中。

最佳答案

您可以使用与此博文 https://blogs.msdn.microsoft.com/kaevans/2008/01/08/modify-message-content-with-wcf/ 中的方法类似的方法

简而言之,您添加 EndpointBehavior 并在其中添加自定义 MessageInspector:

Service1Client proxy = new Service1Client();
proxy.Endpoint.Behaviors.Add(new MyBehavior());  

public class MyBehavior : IEndpointBehavior
{
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            MyInspector inspector = new MyInspector();
            clientRuntime.MessageInspectors.Add(inspector);
        }
}

public class MyInspector : IClientMessageInspector
{
    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
        var xml = "XML of Body goes here";
        var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
        XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());

        Message replacedMessage = Message.CreateMessage(reply.Version, null, xdr);
        replacedMessage.Headers.CopyHeadersFrom(reply.Headers);
        replacedMessage.Properties.CopyProperties(reply.Properties);
        reply = replacedMessage;
    }
}

编辑:添加了MemoryStream,使用来自string 值的数据启动。

关于C# WCF - 创建自定义消息内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36496502/

相关文章:

xml - android View 中经常出现的问题,解析XML时出错: unbound prefix

wcf - WCF session 是否安全?

c# - 如何让 CreatedAtAction 添加查询参数?

c# - 选择最后一个 XML 节点

java - 在 Jython 中解析大型 XML 文档的最佳方法

wcf - WCF 服务中的 IncomingWebRequestContext.UriTemplateMatch null

c# - 使用 SSON cookie 的具有 HTTPS 安全性的 WCF 连接

c# - 使用 C# 或 C++ 在 Windows 10 上的 Bash 上运行 GCC

c# - 如何使用 7zip 压缩目录?

c# - 使对象出列是否会从队列对象中删除引用并允许 GC?