I'm playing with .NET6 and Core Web API. I want to process and return two data formats - JSON and XML. These formats should be strictly separated.
I have added XML formatters and JSON from Newtonsoft, and created two separate methods in the controller. When I post an incorrect JSON to "api/json" it throws an error, but the problem is that the error is in XML, not in JSON.
Can anyone help what should be done to make it return the formats I need?
Program.cs
builder.Services.AddControllers()
.AddXmlSerializerFormatters()
.AddNewtonsoftJson();
MyApiController.cs
[Route("api/json")]
[Consumes("application/json")]
[Produces("application/json")]
[HttpPost]
public IActionResult JsonPost([FromBody] JObject jsonRequest)
{
return Ok(jsonRequest);
}
...
[Route("api/xml")]
[Consumes("application/xml")]
[Produces("application/xml")]
[HttpPost]
public IActionResult XmlPost([FromBody] XDocument xmlRequest)
{
return Ok(xmlRequest);
}
EDIT
When I remove
.AddXmlSerializerFormatters()
then I get the JSON error response, but XML doesn't work.
I need to set somehow that JsonPost() always returns JSON, even there is an unhandled exception, and XmlPost() always returns XML.