How to send XML content with HttpClient.PostAsync?

C#PostHttpclient

C# Problem Overview


I am trying to fulfill this rest api:

public async Task<bool> AddTimetracking(Issue issue, int spentTime)
{
    // POST /rest/issue/{issue}/timetracking/workitem
    var workItem = new WorkItem(spentTime, DateTime.Now);
    var httpContent = new StringContent(workItem.XDocument.ToString());
    var requestUri = string.Format("{0}{1}issue/{2}/timetracking/workitem", url, YoutrackRestUrl, issue.Id);
    var respone = await httpClient.PostAsync(requestUri, httpContent);
    if (!respone.IsSuccessStatusCode)
    {
        throw new InvalidUriException(string.Format("Invalid uri: {0}", requestUri));
    }

    return respone.IsSuccessStatusCode;
}

workItem.XDocument contains the following elements:

<workItem>
  <date>1408566000</date>
  <duration>40</duration>
  <desciption>test</desciption>
</workItem>

I am getting an error from the API: Unsupported Media Type

I really have no idea how to resolve this, help is greatly appreciated. How do I marshall an XML file via a HTTP POST URI, using HttpClient?

C# Solutions


Solution 1 - C#

You might want to set the mediaType in StringContent like below:

var httpContent = new StringContent(workItem.XDocument.ToString(), Encoding.UTF8, "text/xml");

OR

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

Solution 2 - C#

You could use

var respone = await httpClient.PostAsXmlAsync(requestUri, workItem);

https://msdn.microsoft.com/en-us/library/system.net.http.httpclientextensions_methods

Solution 3 - C#

To use Matt Frear's solution you may need to add NuGet Package: Microsoft.AspNet.WebApi.Client

This brings in the extension methods so you can use:

var respone = await httpClient.PostAsXmlAsync<WorkItem>(requestUri, workItem);

This works for the newer .Net 5 so assume will work for asp.net core 3.1.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbasView Question on Stackoverflow
Solution 1 - C#ziddarthView Answer on Stackoverflow
Solution 2 - C#Matt FrearView Answer on Stackoverflow
Solution 3 - C#Saeed NawazView Answer on Stackoverflow