【问题标题】:Posting XML in dotnet 6 web wpi在 dotnet 6 web wpi 中发布 XML
【发布时间】:2022-01-28 17:03:34
【问题描述】:
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 来发布帖子。如果我只发布一个简单的对象,我就可以让它工作。我想了解如何使用嵌套和其他类型的列表发布更复杂的类型。目标是获取 xml 然后返回它。我希望 xml 的结构看起来像上面一样。

【问题讨论】:

    标签: c# asp.net-core .net-core asp.net-core-webapi


    【解决方案1】:

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

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

    并将Produces 属性添加到您的控制器:

    [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();
        }
    }
    

    更新

    您应该在标头中添加 Content-Type: application/xml,或者如果您是从 swagger 中调用它,只需在此处更改请求正文类型:

    【讨论】:

    • 您好,感谢您的回复。我的问题不是输出 xml,而是从帖子正文中解析它。我很难解析到具有其他对象列表的对象。查看我包含的 xml
    • @RomanOwensby 很抱歉答案不清楚,要发布 xml,您需要在请求中添加标头 Content-Type: application/xml 并且您的 api 可以解析 xml 请求
    • P.S 我更新了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2022-06-16
    • 1970-01-01
    • 2011-01-19
    相关资源
    最近更新 更多