Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用HttpWebRequest以XML格式发送请求正文_C#_Api - Fatal编程技术网

C# 如何使用HttpWebRequest以XML格式发送请求正文

C# 如何使用HttpWebRequest以XML格式发送请求正文,c#,api,C#,Api,我不熟悉API。我有一个RESTAPI,它有一个XML格式的请求体和响应体。 我想点击API,但我不知道如何从代码中发送请求体。 我的API的请求主体是- <Person> <Id>12345</Id> <Customer>John Smith</Customer> <Quantity>1</Quantity> <Price>10.00</Price> </Person> 我

我不熟悉API。我有一个RESTAPI,它有一个XML格式的请求体和响应体。 我想点击API,但我不知道如何从代码中发送请求体。 我的API的请求主体是-

<Person>
<Id>12345</Id>
<Customer>John Smith</Customer>
<Quantity>1</Quantity>
<Price>10.00</Price>
</Person>
我在
var data=Encoding.ASCII.GetBytes(person)

它说
无法将表单Person转换为Char[]

我现在不知道如何继续。

希望类似字符串的输入将其转换为字节数组。因此,您必须首先将
peron
转换为字符串/字符数组。因为您想要使用XML,所以应该使用XML序列化程序。例如,使用.NET内置的序列化程序:

// Setup for the person above

// Serialize the person into an XML string
var serializer = new XmlSerializer(typeof(Person));
var sb = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(sb))
{
    serializer.Serialize(xmlWriter, person);
}

// Byte array data to send
var data = Encoding.ASCII.GetBytes(sb.ToString());
 var request = (HttpWebRequest)WebRequest.Create("https://reqbin.com/sample/post/xml");

            Person person = new Person();
            
            Console.WriteLine("Enter ID");
            person.Id = Convert.ToUInt16(Console.ReadLine());

            Console.WriteLine("Enter Name");
            person.Customer = Console.ReadLine();

            Console.WriteLine("Enter Quantity");
            person.Quantity = Convert.ToByte(Console.ReadLine());

            Console.WriteLine("Enter Price");
            person.Price = Convert.ToDecimal(Console.ReadLine());

          
            var data = Encoding.ASCII.GetBytes(person);
// Setup for the person above

// Serialize the person into an XML string
var serializer = new XmlSerializer(typeof(Person));
var sb = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(sb))
{
    serializer.Serialize(xmlWriter, person);
}

// Byte array data to send
var data = Encoding.ASCII.GetBytes(sb.ToString());