Search code examples
c#.netc#-4.0dotnet-httpclient

How to pass XML input to API call using C#


I have below XML input. I need to call API and pass this as input but values will change dynamically. How can I build this input structure?

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Test xmlns="http://tempuri.org/">
      <acc>test</acc>
      <pass>abc</pass>
      <xmlInvData>
<![CDATA[
<MyData>
    <name>test</name>  
    <number>900</number>
</MyData>
]]>
</xmlInvData>
      <username>test</username>
      <password>123</password>    
    </Test>
  </soap:Body>
</soap:Envelope>

I have MyData Class in C# which can be useful to setup name and number values.

But how can I form a complete structure and pass to Api call? soap:Envelop and soap body?

HttpClient httpClient = new HttpClient();

                string requestUri = "https://testurl";

                var byteArray = Encoding.ASCII.GetBytes("username:password");

                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

                HttpResponseMessage response = await httpClient.PostAsync(requestUri, httpContent);

I need to understand how to form httpContent as above my input json.


Solution

  • Assuming you've built the data structure and serialized it to a string called xml:

    var httpContent = new StringContent(xml, Encoding.UTF8, "application/xml");