WEB API 配置 ajax跨域 以及 清理XML格式返回Json 逆水行舟

在项目中使用ajax调webAPI服务时候,通常会遇到以下两种问题,

一、ajax 跨域

跨域需要在API的webconfig中配置此代码:

<!--配置API可跨域-->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>

二、APi返回的数据问题:

有时候调用api方法会返回xml格式,但我们通常需要的是Json格式的数据,甚至调用时会报这个错,

 //The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

虽然还没搞清楚是咋回事,但是找到了解决方法一行代码搞定

//处理方法 在App-Start下的webApiConfig中-加此代码
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

原文地址:https://www.cnblogs.com/zpyplan/p/9565999.html