我正在开发一个 SOAP 服务,我需要<?xml version="1.0" encoding="UTF-8"?>
在传出消息的顶部发送一个格式化的错误消息。
成功的响应在响应顶部没有此版本文本。
我这样做的原因是因为我们正在接管系统和原始供应商的提供,并且只获得了 WSDL 文件。
我有一种方法希望将消息更改为如下所示,但是,当我将其放入新消息中时,它<?xml version="1.0" encoding="UTF-8"?>
会被删除。
public Message ChangeString(Message oldMessage, string from, string to)
{
MemoryStream ms = new MemoryStream();
XmlWriter xw = XmlWriter.Create(ms);
oldMessage.WriteMessage(xw);
xw.Flush();
string body = Encoding.UTF8.GetString(ms.ToArray());
xw.Close();
body = body.Replace(from, to); //// Can see the body being changed here.
ms = new MemoryStream(Encoding.UTF8.GetBytes(body));
XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(ms, new XmlDictionaryReaderQuotas());
Message newMessage = Message.CreateMessage(xdr, int.MaxValue, oldMessage.Version);
newMessage.Properties.CopyProperties(oldMessage.Properties);
return newMessage;
}
调用代码如下
public void ProvideFault(Exception error, MessageVersion messageVersion, ref Message fault)
{
var faultException = new FaultException(error.Message);
var messageFault = faultException.CreateMessageFault();
var message = Message.CreateMessage(messageVersion, messageFault, null);
message = ChangeString(message, message.ToString(), $"<?xml version=\"1.0\" encoding=\"UTF-8\"?>{message.ToString()}");
fault = new ProposalMessage(message);
}
所以,问题是,如何在顶部使用正确的 xml 编码向用户发送消息?
我得到的完整回应是
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Client</faultcode>
<faultstring xml:lang="en-GB">Unable to satisfy web service request at this time.This may relate to the format or sequence of the requests, the status of the requested information or reflect a service issue.</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
- - 编辑 -
var errorFormatter = new ErrorMessageFormatter(new CustomTextMessageEncoderFactory("text/xml", "UTF-8", messageVersion));
var errorByteArray = errorFormatter.WriteMessage(Message.CreateMessage(messageVersion, messageFault, null), int.MaxValue, BufferManager.CreateBufferManager(int.MaxValue, int.MaxValue));
var message = errorFormatter.ReadMessage(errorByteArray, BufferManager.CreateBufferManager(int.MaxValue, int.MaxValue));
fault = new ProposalMessage(message);
是我添加的内容,然后也从故障中删除了 SOAP-ENV。