C# 从web API c返回XML#

C# 从web API c返回XML#,c#,xml,asp.net-web-api,formatter,C#,Xml,Asp.net Web Api,Formatter,只要关注web API,这里就是新手 web Api: [HttpGet] public IHttpActionResult Test() { var doc = new XmlDocument(); XmlElement tournament = (XmlElement)doc.AppendChild(doc.CreateElement("Tournament")); XmlElement match = (XmlElement)

只要关注web API,这里就是新手

web Api:

[HttpGet]
    public IHttpActionResult Test()
    {
        var doc = new XmlDocument();
        XmlElement tournament = (XmlElement)doc.AppendChild(doc.CreateElement("Tournament"));
        XmlElement match = (XmlElement)tournament.AppendChild(doc.CreateElement("Match"));
        match.SetAttribute("ID", "SomeMatch");

        return Ok(doc.InnerXml);
    }
结果:

TournamentMatch ID=“SomeMatch”//Tournament

两个问题:

  • 为什么当我的XML没有这个字符串元素时,它被包装在这个字符串元素中
  • 为什么<转换为“<;”而>转换为“>;”
  • 怎么才能回来呢

    <Tournament>
    <Match ID="SomeMatch" /></Tournament>
    

    由于您正在从操作返回字符串,ASP.Net Web API正在创建等效的XML来表示字符串

    现在,如果要确保API使用XML序列化,客户端可以向请求添加
    accept
    头。或者,通过使用以下构造函数返回
    Content
    ,您可以按照现有方式或在操作本身中指定格式化程序:

    return Content (HttpStatusCodeHere, doc.DocumentElement, Configuration.Formatters.XmlFormatter)
    

    请注意,我没有访问Visual Studio的权限,因此类/属性名称可能不准确。

    由于您正在从操作返回字符串,ASP.Net Web API正在创建等效的XML来表示字符串

    现在,如果要确保API使用XML序列化,客户端可以向请求添加
    accept
    头。或者,通过使用以下构造函数返回
    Content
    ,您可以按照现有方式或在操作本身中指定格式化程序:

    return Content (HttpStatusCodeHere, doc.DocumentElement, Configuration.Formatters.XmlFormatter)
    

    请注意,我没有访问Visual Studio的权限,因此类/属性名称可能不准确。

    您必须返回
    doc.DocumentElement
    ,而不是
    doc.InnerXml

    因为
    doc.InnerXml
    以字符串格式提供xml,所以xml以
    格式显示

    [HttpGet]
            public IHttpActionResult Test()
            {
                var doc = new XmlDocument();
                XmlElement tournament = (XmlElement)doc.AppendChild(doc.CreateElement("Tournament"));
                XmlElement match = (XmlElement)tournament.AppendChild(doc.CreateElement("Match"));
                match.SetAttribute("ID", "SomeMatch");
                return Ok(doc.DocumentElement);                 
            }
    

    所有api返回的输出都是
    xml
    格式,因为默认情况下
    HttpConfiguration
    设置在
    XmlFormatter
    中。

    您必须返回
    doc.DocumentElement
    而不是
    doc.InnerXml

    因为
    doc.InnerXml
    以字符串格式提供xml,所以xml以
    格式显示

    [HttpGet]
            public IHttpActionResult Test()
            {
                var doc = new XmlDocument();
                XmlElement tournament = (XmlElement)doc.AppendChild(doc.CreateElement("Tournament"));
                XmlElement match = (XmlElement)tournament.AppendChild(doc.CreateElement("Match"));
                match.SetAttribute("ID", "SomeMatch");
                return Ok(doc.DocumentElement);                 
            }
    
    所有api返回的输出都是
    xml
    格式,因为默认情况下
    HttpConfiguration
    是在
    XmlFormatter
    中设置的