我正在编写一个库来使用第三方 Web 服务(我显然无法更改)。该库当前设置为 .Net Standard 2.0,以便我可以在当前的应用程序 (.Net Framework 4.6.2) 以及未来可能在 .Net Core 中开发的项目中使用它。这不是一个要求,但如果可能的话我想保持这种方式。
我使用 Microsoft WCF Web 服务参考提供程序实用程序从 WSDL 生成代理类。所以我的基本客户端工厂如下所示:
public static class AuthenticationClientFactory
{
public static AuthenticationClient CreateNew()
{
//Specify the binding to be used for the client.
BasicHttpsBinding binding = new BasicHttpsBinding();
//Specify the address to be used for the client.
EndpointAddress address = new EndpointAddress(Globals.WebServiceAuthenticationURL);
var client = new AuthenticationClient(binding, address);
return client;
}
}
当在上面生成的 AuthenticationClient 上调用“AuthenticateAsync”方法时,将创建如下请求:
<?xml version="1.0" encoding="utf-16"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<h:MessageId i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:h="http://centiro.com/facade/shared/1/0/datacontract" />
</s:Header>
<s:Body>
<AuthenticateRequest xmlns:d3p1="http://schemas.datacontract.org/2004/07/Centiro.Facade.Common.Operations.Authenticate" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://centiro.com/facade/shared/1/0/servicecontract">
<d3p1:Password>Pass123</d3p1:Password>
<d3p1:UserName>User123</d3p1:UserName>
</AuthenticateRequest>
</s:Body>
</s:Envelope>
使用 SoapUI,我针对服务测试了 XML,并收到了“HTTP/1.1 400 Bad Request”。起初,我剥离了肥皂消息中的所有内容,最后将问题范围缩小到 XML 声明。完全剥离 XML 声明或将声明更改为“”允许服务成功处理请求。
所以问题是,我如何完全剥离 XML 声明,或者更好地将声明更改为“utf-8”(我通过 SoapUI 确认可以使用)?
我已经尝试过的事情:
- 将 BasicHttpsBinding 上的 TextEncoding 显式更改为 utf-8。 XML 声明仍然显示 utf-16。
- 创建 CustomBinding,并将 TextMessageEncodingBindingElement 显式设置为 Soap11 和 utf-8 编码。
- 使用 MessageInspector 使用 utf-8 重新编码消息。 (但这最终只会重新编码消息的主体)
看起来这应该是一个如此简单的改变。此时,我已准备好通过 WebClient 对象构建我自己的客户端,以便我可以更好地控制,并且我将自己构建对象和序列化。我在多个地方读到,默认情况下,WCF 自动将所有内容编码为 utf-8,因此我不确定为什么声明一开始就声明“utf-16”。