Web API 不返回 XML 而只是返回 JSON
[HttpGet]
public IHttpActionResult Get(string Account)
{
// other code fo connecting to the SQL seerver and calling the stored procedure
reader = command.ExecuteReader();
List<QueryResult>qresults = new List<QueryResult>();
while (reader.Read())
{
QueryResult qr = new QueryResult();
qr.AccountID = reader["AccountID"].ToString();
qr.CounterSeq = reader["CounterSeq"].ToString();
qresults.Add(qr);
}
DbConnection.Close();
return Ok(qresults);
当我点击 JSON 时,它显示为 [{"AccountID":"Research","CounterSeq":"3"}]
我有两个问题
如何返回文件名为 QueryResult.xml 的响应。
我们如何才能自动返回 XML 而不是 JSON。我不确定在哪里接受 Web API 应用程序中发生的内容。
我是 API 的新手,不确定我遗漏了什么。非常感谢任何帮助
请您参考如下方法:
结果的格式取决于两件事。
- 什么是允许的
- 要求什么
允许的序列化程序
允许的内容取决于 WebApiConfig.cs 中包含的序列化程序。默认情况下,包括 xml 序列化程序和 json 序列化程序。如果您只想为整个 Web 应用程序返回 XML,那么像这样删除 json 格式化程序。
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
客户请求
客户端可以根据 http header content-type 指定他们想要的内容,值为 application/json 或 application/xml取决于他们希望返回数据的格式。
如果客户端未在请求的 header 中指定任何内容,则列表中第一个允许的序列化程序将用作默认值。
