我这里只写基本用法以作记录,具体为什么看下面的文章:
http://www.cnblogs.com/landeanfen/p/5177176.html
http://www.cnblogs.com/moretry/p/4154479.html
Nuget:microsoft.aspnet.webapi.cors,安装到WebApi项目上
web.config:
<appSettings> <add key="cors:allowedMethods" value="*"/> <add key="cors:allowedOrigin" value="http://localhost:63145"/> <add key="cors:allowedHeaders" value="*"/> </appSettings>
/App_Start/WebApiConfig修改一下:
引入命名空间:
using System.Web.Http.Cors;
using System.Configuration;
然后在Register函数里加入这段代码:这样以来就是全部的接口都具有跨域支持
#region 跨域配置 var allowedMethods = ConfigurationManager.AppSettings["cors:allowedMethods"];//跨域支持的请求方式 get,post,put,delete; * 代表所有,多种方式用逗号隔开。 var allowedOrigin = ConfigurationManager.AppSettings["cors:allowedOrigin"];//接受指定域名下的跨域请求,*表示接受任何来源的请求。 var allowedHeaders = ConfigurationManager.AppSettings["cors:allowedHeaders"];// var geduCors = new EnableCorsAttribute(allowedOrigin, allowedHeaders, allowedMethods) { SupportsCredentials = true }; config.EnableCors(geduCors); #endregion
另一个方法,在Controller上面加特性描述,这样只有这个接口支持跨域:
//[EnableCors(origins: "http://localhost:63145", headers: "*", methods: "GET,POST,PUT,DELETE")]//也可以这样用 public class ChargingController : ApiController { /// <summary> /// api/Charging/GetAllChargingData /// </summary> /// <returns></returns> [HttpGet] public string GetAllChargingData() { //HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent("success", Encoding.GetEncoding("UTF-8"), "application/json") }; //return result; return ToJsonTran.ToJson2("success"); } }
ToJsonTran是什么:
public class ToJsonTran { public static HttpResponseMessage ToJson(Object obj) { String str; if (obj is String || obj is Char) { str = obj.ToString(); } else { JavaScriptSerializer serializer = new JavaScriptSerializer(); str = serializer.Serialize(obj); } HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; return result; } public static string ToJson2(Object obj) { String str; if (obj is String || obj is Char) { str = obj.ToString(); } else { JavaScriptSerializer serializer = new JavaScriptSerializer(); str = serializer.Serialize(obj); } return str; } }
页面上面的js测试跨域:
<script> jQuery.support.cors = true; var ApiUrl = "http://localhost:58068/"; $(function () { $.ajax({ type: "get", url: ApiUrl + "api/Charging/GetAllChargingData", data: {}, success: function (data, status) { debugger; if (status == "success") { $("#div_test").html(data); } }, error: function (e) { debugger; $("#div_test").html("Error"); }, complete: function () { } }); }); </script> 测试结果:<div id="div_test"></div>
POST请求:
function test1() { $.ajax({ type: "POST", url: ApiUrl + "OfficialStoryInfo/GetJsonPDataByID", contentType: 'application/json', data: JSON.stringify({ ID: 711, callback: "" }), success: function (d, status) { debugger; if (status == "success") { var StoryInfo = $.parseJSON(d).Data; if (StoryInfo != null && StoryInfo != undefined) { var Name = StoryInfo.Name; var Description = StoryInfo.Description; document.title = Name; $("meta[name='apple-mobile-web-app-title']").attr('content', Name); $("#div_test").html(Description); } } }, error: function (e) { debugger; $("#div_test").html("Error"); }, complete: function () { } }); }
这里的post请求,注意 contentType 和 data 里的 JSON.stringify() ,这样后台Api接口可以使用 dynamic 参数接收。注意看开头引用的那两篇文章。
注意:jQuery.support.cors = true;因为有些浏览器不支持js跨域,加上这句。
最近又发现了一个方法,只不过我还没试过,如下:
在web.config的<system.webServer>节点下面加入配置:
<!--跨域配置-->
<httpProtocol>
<customHeaders>
<add name=
"Access-Control-Allow-Origin"
value=
"*"
/>
<add name=
"Access-Control-Max-Age"
value=
"30"
/>
<add name=
"Access-Control-Allow-Methods"
value=
"GET,POST,OPTIONS"
/>
<add name=
"Access-Control-Allow-Headers"
value=
"Content-Type, Accept"
/>
</customHeaders>
</httpProtocol>