【问题标题】:How to create HTTP POST Request Body content with WCF REST (Starter Kit)如何使用 WCF REST(入门工具包)创建 HTTP POST 请求正文内容
【发布时间】:2015-09-17 16:58:55
【问题描述】:

我正在与ZenDesk 集成一个应用程序。他们有一个REST API。我需要在请求正文中发送 POX。我正在使用 WCF REST Starter Kit。

如何以编程方式将我的 xml 添加到请求正文中?

这是我的单元测试:

        [Test]
        public void Can_create_user()
        {
            // Arrange
            http = new HttpClient("http://myapp.zendesk.com/");
            http.TransportSettings.Credentials = new NetworkCredential
                                               ("joe@admin.com", "passW0rd");
            http.DefaultHeaders.Accept.Add("application/xml");
            var form = new HttpUrlEncodedForm();
            var expectedStatusCode = 201;

            var request = new XDocument(
                new XElement("user",
                             new XElement("email", "joe@user.com"),
                             new XElement("name", "Joe User"),
                             new XElement("roles", "4"),
                             new XElement("restriction-id", "4")));

            form.Add("body", request.ToString());

            // Act
            var response = http.Post("users.xml", form.CreateHttpContent());
            var content = response.Content.ReadAsString();

            // Assert
            response.EnsureStatusIs(expectedStatusCode);

【问题讨论】:

  • 我最近写了一篇关于您可以使用 HttpContent 执行的其他一些操作的博客文章。 bizcoder.com/index.php/2009/12/09/…
  • 干杯达雷尔。非常有用的博文。我已经注意到它:)

标签: xml wcf api rest


【解决方案1】:

解决方法是使用静态方法Microsoft.Http.HttpContent.Create()

var response = http.Post("users.xml", HttpContent.Create(requestXML.ToString()));

【讨论】:

  • 另外,替换这个 http.DefaultHeaders.Accept.Add("application/xml");用这个 http.DefaultHeaders.Add("Content-Type", "application/xml; charset=utf-8");
猜你喜欢
  • 2010-09-20
  • 1970-01-01
  • 2011-07-06
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 2019-01-10
  • 2011-10-19
相关资源
最近更新 更多