C# - How to put or post XML using the HttpClient - updated for 2023

It is quite easy to send XML using the HttpClient. In order to do this you need to use the StringContent object, provide it with an XML string, an encoding format and a mediatype. The XML string provided will form the body of the HTTP request, a full example on how to do this can be seen below:

var httpClient = new HttpClient();
var someXmlString = "<SomeDto><SomeTag>somevalue</SomeTag></SomeDto>";
var stringContent = new StringContent(someXmlString, Encoding.UTF8, "application/xml");
var response = await httpClient.PostAsync("/someurl", stringContent);

The above can also be used in combination with PutAsync instead of PostAsync:

var httpClient = new HttpClient();
var someXmlString = "<SomeDto><SomeTag>somevalue</SomeTag></SomeDto>";
var stringContent = new StringContent(someXmlString, Encoding.UTF8, "application/xml");
var response = await httpClient.PutAsync("/someurl", stringContent);

You may also want to use "text/xml" instead of "application/xml" depending on what the endpoint you are using accepts. You can read more about the difference here.

That is all!

That is it, I hope this post was of help to you, please leave a comment down below, I read all of them!