我尝试了这段代码:

WebApiConfig.cs

config.Formatters.XmlFormatter.UseXmlSerializer = true;


在我的API控制器代码中:

    [Route("fetch")]
    public IEnumerable<S1.Location> Get()
    {
        var location = _locationService.GetAll();
        var loList = new List<S1.Location>();
        foreach (Location loc in location)
        {
            var lo = new S1.Location()
            {
                Id = loc.ID.ToString(),
                Title = loc.Title
            };
            loList.Add(lo);
        }
        return loList;
    }


而Location类定义了这一点:

[XmlRoot("MyLocation")]
public class Location
{
    [XmlAttribute]
    public string Id { get; set; }
    [XmlAttribute]
    public string Title { get; set; }
}


我期待的结果

<MyLocation>
    <Location Id="3" Title="Causeway Bay1"/>
    <Location Id="5" Title="Kowloon Bay"/>
    <Location Id="6" Title="Kowloon Bay"/>
</Location>


但收到一个

<ArrayOfLocation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Location Id="3" Title="Causeway Bay1"/>
    <Location Id="5" Title="Kowloon Bay"/>
    <Location Id="6" Title="Kowloon Bay"/>
</Location>


为什么根元素不变?

最佳答案

您必须更改使用从列表继承的自定义类

 [XmlType("MyLocation")]
        public class MyLocation:List<Location>
        {

        }


并在您的get方法中使用它

 public MyLocation Get()
    {
        var location = _locationService.GetAll();
        var loList = new MyLocation();
        foreach (Location loc in location)
        {
            var lo = new S1.Location()
            {
                Id = loc.ID.ToString(),
                Title = loc.Title
            };
            loList.Add(lo);
        }
        return loList;
    }

关于c# - Web API根元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42698122/

10-10 22:44