Asp.Net WebAPI配置接口返回数据类型为Json格式

1、默认状况下WebApihtml

对于没有指定请求数据类型类型的请求,返回数据类型为Xml格式json

例如:从浏览器直接输入地址,或者默认的XMLRequest,或者AngularJs的get请求等。跨域

对于有循环引用的也会抛出异常““ObjectContent`1”类型未能序列化内容类型“application/xml; charset=utf-8”的响应正文。”浏览器

 

2、设置返回格式为Json数据app

1.修改配置,这对全部的接口都生效post

找到Global.asax文件,在Application_Start()方法中添加一句: spa

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear()

2.针对某一个接口设置.net

解决的方法是自定义返回类型(返回类型为HttpResponseMessage) code

 
public HttpResponseMessage PostUserName(User user) 
{ 
String userName = user.userName; 
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(userName,Encoding.GetEncoding("UTF-8"), "application/json") }; 
return result; 
} 

 

更多:orm

Asp.Net WebApi 项目及依赖整理

Asp.Net WebApi+Microsoft.AspNet.WebApi.Core 启用CORS跨域访问

使Asp.net WebApi支持JSONP和Cors跨域访问

自定义序列化处理:www.cnblogs.com/acles/archive/2013/06/21/3147667.html

相关文章
相关标签/搜索