Reputation: 13
builder.Services.AddControllers().AddXmlSerializerFormatters(); //I added xml
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
public class WeatherForecastList //Class I want to post in xml
{
public List<WeatherForecast> Forecasts { get; set; }
}
[HttpPost] //Experimental method
public ActionResult<WeatherForecastList> GetWeather([FromBodyAttribute]
WeatherForecastList WeatherForecast)
{
return Ok(WeatherForecast);
}
<WeatherForecastList>
<Forecasts>
<WeatherForecast>
.
.
</WeatherForecast>
</Forecasts
</WeatherForecastList>
I am currently experimenting with making posts using XML instead of JSON in dotnet 6. I can get it to work if I just post a simple object. I would like to understand how to post more complex types with nesting and lists of other types. The goal is to get the xml and then return it. Id like the structure of the xml to look something like above.
Upvotes: 1
Views: 1669
Reputation: 3545
You need to add xml formatters in Program.cs
:
builder.Services.AddControllers()
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
and add Produces
attribute to your controller:
[ApiController]
[Route("[controller]")]
[Produces("application/xml")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
Update
You should add Content-Type: application/xml
in headers, or if you are calling it from swagger just change request body type here:
Upvotes: 1