c# WCF HTTP rest客户端带有WebHttpBinding/Behavior,用于在请求体中发布原始数据
本文关键字:请求 用于 原始数据 Behavior rest HTTP WCF 客户端 WebHttpBinding | 更新日期: 2023-09-27 18:17:07
我有一个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,我失去了简单的配置在我的应用程序的配置文件!
提前非常感谢!
我通过向我的ClientBase继承类添加以下代码找到了解决方案:
public class HttpXmlClient : ClientBase<IHttpXmlClient>, IHttpXmlClient
{
public void Send(Stream data)
{
using (new OperationContextScope((IContextChannel) Channel))
{
var request = WebOperationContext.Current.OutgoingRequest;
request.ContentType = "text/xml;charset=UTF-8";
Channel.Send(data);
}
}
}