c#WCF带有WebHttpBinding的HTTP rest客户端/用于在请求体中发布RAW数据的行为

时间:2013-06-05 12:39:27

标签: c# xml wcf http-post

我有一个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);
}

除了“内容类型”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,我在应用程序的配置文件中放松了简单的配置!

非常感谢你!

1 个答案:

答案 0 :(得分:0)

我通过将以下代码添加到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);
    }
  }
}