web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面就介绍两种方法:
方法一:(改配置法)
找到Global.asax文件,在Application_Start()方法中添加一句:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
修改后:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
// 使api返回为json
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
这样返回的结果就都是json类型了,但有个不好的地方,如果返回的结果是String类型,如123,返回的json就会变成"123";
解决的方法是自定义返回类型(返回类型为HttpResponseMessage)
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;
}