如何将XML发送到asp.net Web api调用?

时间:2017-06-28 23:25:26

标签: asp.net asp.net-web-api

我正在尝试按如下方式进行Web API Post方法调用,但它没有按预期工作,xmlcontent似乎没问题,但是当发送请求并且响应抛出错误时,格式化似乎搞砸了,我仔细检查了来自python的XML并且它有效,是否有更好的方法来创建和发送XML?我做错了什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;

namespace WebApiXML
{
    public class Program
    {
        static void Main(string[] args)
        {
            testWCF2(); //Or whatever
            Console.ReadLine();
        }
        public static async Task testWCF2()
        {
            string xmlcontent = @"<SoftwareProductBuild>
  <BuildSource>DATASOURCE</BuildSource>
  <BuiltBy>username1</BuiltBy>
  <CreatedBy>username1</CreatedBy>
  <Name>username1_1959965_1969310_524f7fef-5b37-11e7-b4ee-f0921c133f10_UL.AB.1.2_test2</Name>
  <Status>Approved</Status>
  <BuiltOn>2017-06-27T06:20:30.275690</BuiltOn>
  <Tag>username1_1959965_1969310_524f7fef-5b37-11e7-b4ee-f0921c133f10_test2</Tag>
  <Keywords>
    <KeywordInfo>
      <Name>subystem</Name>
    </KeywordInfo>
  </Keywords>
  <SoftwareImageBuilds>
    <SoftwareImageBuild>
      <Type>LA</Type>
      <Name>username1_1959965_1969310_524f7fef-5b37-11e7-b4ee-f0921c133f10_UL.AB.1.2_test2</Name>
      <Location>\\location1\data1\PRECOMMIT_OS_DEF</Location>
      <Variant>PRECOMMIT_OS_DEF</Variant>
      <LoadType>Direct</LoadType>
      <Target>msm8998</Target>
      <SoftwareImages>
        <SoftwareImage>
          <Name>UL.AB.1.2</Name>
        </SoftwareImage>
      </SoftwareImages>
    </SoftwareImageBuild>
  </SoftwareImageBuilds>
</SoftwareProductBuild>";
            #region using
            using (var client = new System.Net.Http.HttpClient())
            {
                var response = await client.PostAsXmlAsync("http://server:8100/api/SoftwareProductBuild", xmlcontent);

                if (!response.IsSuccessStatusCode)
                {
                    //throw new InvalidUriException("Some error with details.");
                    Console.WriteLine(response);
                }
                Console.WriteLine("Printing DEV Pool Response\n");
            }
            #endregion
           //return null;
        }
    }

}

1 个答案:

答案 0 :(得分:1)

PostAsXmlAsync将尝试序列化传递给它的对象。所以你有一个包含XML的字符串,然后尝试将字符串发布为XML(双序列化)。

使用StringContent,为其提供XML字符串值并将内容类型设置为适当的媒体类型,然后发布。即client.PostAsync(url, content)

using (var client = new System.Net.Http.HttpClient()) {
    var url = "http://server:8100/api/SoftwareProductBuild";
    var content = new StringContent(xmlcontent, Encoding.UTF8, "application/xml");
    var response = await client.PostAsync(url, content);
    if (response.IsSuccessStatusCode) {
        var responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine("Printing DEV Pool Response\n");
        Console.WriteLine(responseBody);
    } else {
        Console.WriteLine(string.Format("Bad Response {0} \n", response.StatusCode.ToString()));
    }       
}