C# 从web API c返回XML#
只要关注web API,这里就是新手 web Api: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)
[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
两个问题:
<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
中设置的