【发布时间】:2017-01-27 03:49:27
【问题描述】:
我有一个 web api 方法,它以格式作为参数,提供返回 xml 和 json。该方法返回的数据类型是 DataTable。在 json 格式中,一切看起来都很好,但在 xml 格式中,数据表的架构和一些其他属性在 xml 节点中也返回。如何返回仅包含数据表数据的简单 xml?另外,我在 WebApiConfig 中使用 QueryStringMapping。
这是 WebApiConfig 代码
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("format", "json", new MediaTypeHeaderValue("application/json")));
config.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("format", "xml", new MediaTypeHeaderValue("application/xml")));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
}
这是控制器方法的伪代码
[BasicAuthentication]
[Route("api/{tablename}")]
[HttpGet]
public IHttpActionResult Get(string tablename, string orders = "", int limit = 100)
{
DataTable dt = new DataTable{TableName="resource"};
//... Database connection and getting result
return Ok(new Response{ limit = limit,count=dt.Rows.Count, data =dt });
}
和响应模型
public class Response
{
public int limit { get; set; }
public int count { get; set; }
public DataTable data { get; set; }
}
返回的xml示例
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<limit>1</limit>
<count>1</count>
<data>
<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="resource" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="resource">
<xs:complexType>
<xs:sequence>
<xs:element name="ID" type="xs:long" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<DocumentElement>
<resource diffgr:id="resource1" msdata:rowOrder="0">
<ID>1</ID>
</resource>
</DocumentElement>
</diffgr:diffgram>
</data>
</Response>
综上所述,我只想返回数据节点中的资源节点,不带任何属性。
【问题讨论】:
-
在这个问题的示例中使用属性stackoverflow.com/questions/12590801/…
-
有些奇怪的是,关于 json 的格式化程序正在工作,例如 Intended,但有关 xml 的格式化,例如 config.Formatters.XmlFormatter.UseXmlSerializer = true;在 WebApiConfig 中不起作用
-
json 没有与 xml 相同的命名空间和模式信息,这就是为什么它与 json 配合得更好
-
也许你需要写一个新的xmlformatter stackoverflow.com/questions/17327677/…
-
@Thorarins 你是对的。这个问题的答案解决了我的问题。在问之前我还没有看到这个答案。问题都与 Datatable 对象有关。 stackoverflow.com/questions/14571927/net-webapi-datatable.
标签: c# xml asp.net-mvc-5 asp.net-web-api2 xml-formatting