簡體   English   中英

在 dotnet 6 web wpi 中發布 XML

[英]Posting XML in dotnet 6 web wpi

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>

我目前正在嘗試在 dotnet 6 中使用 XML 而不是 JSON 發布帖子。如果我只發布一個簡單的 object,我就可以讓它工作。 我想了解如何使用嵌套和其他類型的列表發布更復雜的類型。 目標是獲取 xml 然后返回。 我喜歡 xml 的結構看起來像上面的樣子。

您需要在Program.cs中添加 xml 格式化程序:

builder.Services.AddControllers()
    .AddXmlSerializerFormatters()
    .AddXmlDataContractSerializerFormatters();

並將Produces屬性添加到您的 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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM