WebApi 内容协商 简单区分JSON 和 Xml
Accept:响应可接收的媒体类型,如"application/json"、"application/xml",或者自定义媒体类型,如"application/vnd.example+xml"。
当我们希望接收到的是JSON时
private void button2_Click(object sender, EventArgs e) { HttpWebRequest request=(HttpWebRequest) WebRequest.Create("http://localhost:20137/api/Demo?Name=张三&Gender=M&age=22"); request.Method = "GET"; request.Accept = "application/json" using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string result = reader.ReadToEnd(); this.textBox1.Text = result; } } }
public IHttpActionResult Get([FromUri]Person person) { return Ok(person); }
返回 {"Name":"张三","Gender":"M","Age":22}
当我们希望返回的是XML时
private void button2_Click(object sender, EventArgs e) { HttpWebRequest request=(HttpWebRequest) WebRequest.Create("http://localhost:20137/api/Demo?Name=张三&Gender=M&age=22"); request.Method = "GET"; request.Accept = "application/xml"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string result = reader.ReadToEnd(); this.textBox1.Text = result; } } }
public IHttpActionResult Get([FromUri]Person person) { return Ok(person); }
返回
<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebApi.Models">
<Age>22</Age>
<Gender>M</Gender>
<Name>张三</Name>
</Person>