.net webapi 返回json格式
电脑版发表于:2020/1/2 17:06
.net framework中webapi默认返回的是xml格式,想要返回json格式可以如下操作。
方法一:使用HttpResponseMessage单个返回json
public HttpResponseMessage Get(int id) { HttpResponseMessage httpReponseMessage = new HttpResponseMessage(); string jsonstr = JsonConvert.SerializeObject(new PetViewModel { Age = 10, UserName = "ss" }); httpReponseMessage.Content = new StringContent(jsonstr); return httpReponseMessage; }
方法二:全局方法,删除到XmlFormatter
System.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
只是vs2012中可以,vs2017中就不行了