. NET основной веб-API, как изменить root имя XML, возвращаемого при использовании IAsyncEnumerable? - PullRequest
0 голосов
/ 25 марта 2020

Я хотел бы использовать новый IAsyncEnumerable<T> в моем. net core 3.1 web api. Это работает хорошо, за исключением того, что меня не устраивает название элемента XML root. Похоже, это ArrayOfX, и я хотел бы что-то вроде Xs. Как мне этого добиться?

Чтобы быть более точным c. Мой контроллер:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    [HttpGet]
    public async IAsyncEnumerable<WeatherForecast> Get()
    {
        await Task.Delay(0);
        var rng = new Random();

        for (var index = 1; index < 5; index++)
        {
            yield return new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            };
        }
    }
}

public class WeatherForecast
{
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public string Summary { get; set; }
}

В Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddMvcCore(options =>
        {
            options.OutputFormatters.Clear(); // Remove json for simplicity
            options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
        });
}

И вывод XML:

<ArrayOfWeatherForecast xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><WeatherForecast><Date>2020-03-26T08:39:59.2303161+01:00</Date><TemperatureC>-13</TemperatureC><Summary>Warm</Summary></WeatherForecast><WeatherForecast><Date>2020-03-27T08:39:59.2389359+01:00</Date><TemperatureC>22</TemperatureC><Summary>Sweltering</Summary></WeatherForecast><WeatherForecast><Date>2020-03-28T08:39:59.2389696+01:00</Date><TemperatureC>33</TemperatureC><Summary>Scorching</Summary></WeatherForecast><WeatherForecast><Date>2020-03-29T08:39:59.2389719+02:00</Date><TemperatureC>-2</TemperatureC><Summary>Bracing</Summary></WeatherForecast></ArrayOfWeatherForecast>

Как получить WeatherForecasts вместо ArrayOfWeatherForecast

1 Ответ

1 голос
/ 26 марта 2020

Вы можете написать свой собственный XmlSerializerOutputFormatter, как показано ниже:

public class MyCustomXmlSerializerOutputFormatter : XmlSerializerOutputFormatter
{
    protected override void Serialize(XmlSerializer xmlSerializer, XmlWriter xmlWriter, object value)
    {

        xmlSerializer = new XmlSerializer(typeof(List<WeatherForecast>) ,new XmlRootAttribute("WeatherForecasts"));

        xmlSerializer.Serialize(xmlWriter, value);
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddMvcCore(options =>
        {
            options.OutputFormatters.Clear(); // Remove json for simplicity
            options.OutputFormatters.Add(new MyCustomXmlSerializerOutputFormatter());
        });
    }

Результат:

enter image description here

...