In a previous post I showed how you can send XML using the HttpClient in asp.net core, using the following code snippet:
var httpClient = new HttpClient();
var someXmlString = "<SomeDto><SomeTag>somevalue</SomeTag></SomeDto>";
var stringContent = new StringContent(someXmlString, Encoding.UTF8, "application/xml");
var respone = await httpClient.PutAsync("https://localhost:44351/weatherforecast", stringContent);
In this post I show how you can set up an endpoint to receive XML, starting from scratch in the standard weatherforecast application.
Receiving XML in a controller endpoint
First we need to add the dataContractSerializer so that our application knows how to serialize and deserialize the XML. This is done by adding the following line in your startup.cs:
services.AddControllers().AddXmlDataContractSerializerFormatters();
We then add a new PUT endpoint to our controller, which accepts a DTO that contains our XML input:
[HttpPut()]
public ActionResult Put(SomeDto dto)
{
return Ok();
}
We define the DTO according to the XML sent by the client, with the member/element SomeTag:
[DataContract(Name = "SomeDto", Namespace = "")]
public class SomeDto
{
[DataMember]
public string SomeTag { get; set; }
}
Now when we make a request using the client in the first code snippet, we receive a 200 response code. We can also see that the property SomeTag
is assigned the value someValue
when debugging the controller.
That is it, I hope you found this helpful! Please leave a comment down below :)