脚本宝典收集整理的这篇文章主要介绍了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>
以上是脚本宝典为你收集整理的WebApi 内容协商 简单区分JSON 和 Xml全部内容,希望文章能够帮你解决WebApi 内容协商 简单区分JSON 和 Xml所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。