gpt4 book ai didi

xml - 当服务的响应是非法的 XML 时,如何清理它?

转载 作者:行者123 更新时间:2023-12-04 06:11:29 26 4
gpt4 key购买 nike

所以我相信我理解这些概念,我认为我应该使用 IClientMessageInspector但在我看来,所有工具都必须与 System.ServiceModel.Channels.Message 的主体一起工作需要在 .NET 中使用 XML 对象,但我不能这样做,因为这个消息的正文是非法的 XML。最终,消息是这样的:

[random number]
<validXml />
[other random number]

例如:
379
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<ns1:getVersionResponse>
<ns1:getVersionResponse xsi:type="xsd:string">1.2.3</ns1:getVersionResponse>
</ns1:getVersionResponse>
</soapenv:Body>
</soapenv:Envelope>
0

这是一个可以工作的例子,除了上面是无效的 XML(这正是我首先这样做的原因!):
public class CleanRandomNumbersInspector : IClientMessageInspector
{
public void AfterReceiveReply(ref Message reply, object correlationState)
{
const int tenMegabytes = 10485760;
var buffer = reply.CreateBufferedCopy(tenMegabytes);
var copyToRead = buffer.CreateMessage();
string body;

using (var reader = copyToRead.GetReaderAtBodyContents())
{
body = reader.ReadOuterXml();
}

// Now that we have the text, modify it
body = body.Trim('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0');

// Shove it back into the message
var copyToPassOn = buffer.CreateMessage();
using (var stream = GenerateStreamFromString(body))
{
var writer = XmlDictionaryWriter.CreateTextWriter(stream);
copyToPassOn.WriteBodyContents(writer);
}

// Implement this method to inspect/modify messages after a message
// is received but prior to passing it back to the client
Console.WriteLine("AfterReceiveReply called");
}

public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
// GNDN
return null;
}

private static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
}

最终,是的,我知道,这是一项糟糕的服务。但是,我需要在对方解决此问题之前消耗它。我该怎么做?

最佳答案

您可以通过使用自定义消息编码器来实现(包装原始编码器,在 MessageEncoder.ReadMessage 的实现中,您将在将正文移交给原始编码器之前删除任何无关字节)。

但这真的是糟糕的 XML 吗?这看起来像是分块传输编码(参见 http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html ,第 3.6.1 节) - 检查 HTTP header 以查看是否找到了 Transfer-Encoding: chunked header ,然后由 HTTP 传输来删除这些块。 WCF中的HTTP传输可以处理这些,你在哪里看到这个问题?

关于xml - 当服务的响应是非法的 XML 时,如何清理它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7726555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com