[WEB API] CLIENT 指定请求及回应格式(XML/JSON)

[Web API] Client 指定请求及响应格式(xml/json)

Web API 支持的格式请参考

http://www.asp.net/web-api/overview/formats-and-model-binding

本篇则要演练xml/json

回应 Get

定义 Header:Content-Type 定义 QueryString

请求 Post

POST json 数据 POST xml 数据

回应 Get

定义 Header:Content-Type

测试工具:本来想用 postman 但是设定 Content-Type 一直无法成功,尝试一段时间便改用 fiddler

指定 json:application/json

指定 xml:application/xml

[]

观察回传格式

[]

定义 QueryString

在 WebApiConfig.cs 的 Register 方法加上

config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"); 

在网址列加上 ?$format=xml,便可以指定回传格式

[]

参考:http://code.msdn.microsoft.com/Support-format-in-ASPNET-e3785b2a

请求 Post

POST json 数据

{
"ISBN":"111","AuthiorName":"空","BookName":"空","Category":"空","Price":1
}

[]

回传结果

[]

POST Xml

<Product xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebAPI_CRUD.Models">
<AuthiorName>周家安</AuthiorName>
<BookName>Windows Phone8开发技巧与案例精解</BookName>
<Category>.NET</Category>
<ISBN>9787111412304</ISBN>
<Price>69</Price>
</Product>

步骤如下:

[]

回传结果

[]

原文地址:https://www.cnblogs.com/Alex80/p/8672974.html