The HTTP 415 status code is "Unsupported Media Type" and you're using XML when these days the default is JSON.
So add XML support:
builder.Services.AddControllers().AddXmlSerializerFormatters();
You'll probably need to install a nuget package, let Visual Studio intellisense guide you to choosing the right package.
Here I did it myself, I've never seen [FromBody] used for XML, only JSON and it gave me issues. Therefore I used the request argument. [FromBody] might work for XML see here: Minimal API how to make FromBody accept both x-www-form-urlencoded and json?
app.MapPost("/api/todo", async (HttpRequest request) =>
{
var serializer = new XmlSerializer(typeof(ToDoRequest));
ToDoRequest toDoRequest;
using (var memoryStream = new MemoryStream())
{
await request.Body.CopyToAsync(memoryStream);
memoryStream.Position = 0;
toDoRequest = (ToDoRequest)serializer.Deserialize(memoryStream);
}
// For demonstration, return a simple string response
return Results.Ok($"Received ToDo with Id: {toDoRequest.Id} and Description: {toDoRequest.Description}");
})
.Accepts<ToDoRequest>("application/xml")
.AllowAnonymous();
public class ToDoRequest
{
public int Id { get; set; }
public string Description { get; set; }
}
The Project should have a file with a http extension you use as a Rest Client, eg:
@XmlExportApi_HostAddress = http://localhost:5165
### Weather Example
GET {{XmlExportApi_HostAddress}}/weatherforecast/
Accept: application/json
### Add a To Do
POST {{XmlExportApi_HostAddress}}/api/todo/
Accept: application/xml
Content-Type: application/xml
<ToDoRequest>
<Id>1</Id>
<Description>This is how its done</Description>
</ToDoRequest>
