ahs*_*ant 1 c# xml formatter asp.net-web-api
只要是关于Web API的新手。
网络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);
}
Run Code Online (Sandbox Code Playgroud)
结果:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"><Tournament><Match ID="SomeMatch" /></Tournament></string>
两个问题:
以及如何取回
<Tournament>
<Match ID="SomeMatch" /></Tournament>
Run Code Online (Sandbox Code Playgroud)
由于您要从操作中返回字符串,因此ASP.Net Web API会创建等效的XML来表示字符串。
现在,如果要确保API使用XML序列化,则客户端可以将accept标头添加到请求中。另外,您可以Content使用以下构造函数返回,从而以自己的方式或在操作本身中指定格式化程序:
return Content (HttpStatusCodeHere, doc.DocumentElement, Configuration.Formatters.XmlFormatter)
Run Code Online (Sandbox Code Playgroud)
请注意,我无权访问Visual Studio,因此类/属性名称可能不正确。