我有一个要连接的 HTTP REST 服务端点以发送 RAW 格式的 XML 流。因此,我创建了一个客户端服务合同“IHttpXmlClient”,其中包含相应的 ClientBase 继承实现。
using System.ServiceModel.Web;
using System.ServiceModel;
using System.IO;
namespace MyNamespace
{
[ServiceContract]
public interface IHttpXmlClient
{
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, Method = "POST")]
void Send(Stream data);
}
public class HttpXmlClient : ClientBase<IHttpXmlClient>, IHttpXmlClient
{
public void Send(Stream data)
{
Channel.Send(data);
}
}
}
作为配置,我在 App.config 中定义了以下内容:
<system.serviceModel>
<client>
<endpoint address="http://thehttpxmlserver.com:8000/receiver?client=itsme"
binding="webHttpBinding"
bindingConfiguration="webHttp_HttpXmlClient"
contract="MyNamespace.IHttpXmlClient"
behaviorConfiguration="HttpXmlClientEndpointBehavior">
</endpoint>
</client>
<bindings>
<webHttpBinding>
<binding name="webHttp_HttpXmlClient">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" />
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="HttpXmlClientEndpointBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
连接 HTTP REST 服务端点并发送相应 XML 数据的实现如下所示:
var myXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><root>Hello World</root>";
using (var data = new MemoryStream(Encoding.UTF8.GetBytes(myXml)))
{
var client = new HttpXmlClient();
client.ClientCredentials.UserName.UserName = "myuser";
client.ClientCredentials.UserName.Password = "mypassword";
client.Open();
client.Send(data);
}
除了“content-type”HTTP 标头包含错误信息外,一切都运行良好。我使用 fiddler 从我的机器跟踪原始传出信息。结果如下:
POST http://thehttpxmlserver.com:8000/receiver?client=itsme HTTP/1.1
Content-Type: application/octet-stream
Authorization: Basic bXl1c2VyOm15cGFzc3dvcmQ=
Host: thehttpxmlserver.com:8000
Content-Length: 65
Expect: 100-continue
<?xml version="1.0" encoding="utf-8"?><root>Hello World</root>
我想要的是将“content-type”标头设置为值“text/xml;charset=UTF-8”。这有可能吗?当然,我想保留上面的实现,而且我绝对不想实现手动 WebRequest,因为我在应用程序的配置文件中丢失了简单的配置!
非常感谢您!