標籤:
Web Api的優缺點就不說了,直接說怎麼跨域,我搜了一下,主要是有兩種。
一,ASP.NET Web API支援JSONP,分兩種
1,利用JsonMediaTypeFormatter,具體參考這裡:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-03.html
上代碼:
建立JsonpMediaTypeFormatter類:
public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter { private string callbackQueryParameter; public JsonpMediaTypeFormatter() { SupportedMediaTypes.Add(DefaultMediaType); SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript")); MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp", DefaultMediaType)); } public string CallbackQueryParameter { get { return callbackQueryParameter ?? "callback"; } set { callbackQueryParameter = value; } } /// <summary> /// 將對象序列化後的JSON字串填充到JavaScript回呼函數中 /// </summary> /// <param name="type"></param> /// <param name="value"></param> /// <param name="stream"></param> /// <param name="content"></param> /// <param name="transportContext"></param> /// <returns></returns> public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext) { string callback; if (IsJsonpRequest(out callback)) { return Task.Factory.StartNew(() => { var writer = new StreamWriter(stream); writer.Write(callback + "("); writer.Flush(); base.WriteToStreamAsync(type, value, stream, content, transportContext).Wait(); writer.Write(")"); writer.Flush(); }); } else { return base.WriteToStreamAsync(type, value, stream, content, transportContext); } } /// <summary> /// 判斷是否為跨域請求 /// </summary> /// <param name="callback"></param> /// <returns></returns> private bool IsJsonpRequest(out string callback) { callback = null; if (HttpContext.Current.Request.HttpMethod != "GET") return false; callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter]; return !string.IsNullOrEmpty(callback); } }
2,利用ActionFilterAttribute ,具體參考這裡:http://stackoverflow.com/questions/9421312/jsonp-with-asp-net-web-api/18206518#18206518
代碼:
建立 JsonCallbackAttribute 類
public class JsonCallbackAttribute : ActionFilterAttribute { private const string CallbackQueryParameter = "callback"; public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { var callback = string.Empty; if (IsJosnp(out callback)) { var jsonBuilder = new StringBuilder(callback); jsonBuilder.AppendFormat("({0})", actionExecutedContext.Response.Content.ReadAsStringAsync().Result); actionExecutedContext.Response.Content = new StringContent("C(\"a\")"); } base.OnActionExecuted(actionExecutedContext); } private bool IsJosnp(out string callback) { callback = System.Web.HttpContext.Current.Request.QueryString[CallbackQueryParameter]; return !string.IsNullOrEmpty(callback); } }
在Global.asax中註冊JsonCallbackAttribute
GlobalConfiguration.Configuration.Filters.Add(new JsonCallbackAttribute());
二,使用 Microsoft ASP.NET Web API 2 Cross-Origin Suppor
使用 NuGe 安裝 Microsoft ASP.NET Web API 2 Cross-Origin Support,這裡說的很詳細
然後在Global.asax中開啟針對CORS的支援,EnableCors加不加無影響的樣子。
測試執行個體:
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://cdn.bootcss.com/jquery/2.1.3/jquery.min.js"></script> <title>測試 WebApi 跨域</title></head><body> <form id="form1" runat="server"> <input type="button" id="btnGet" value="Get 點擊跨域查詢資料" /> <div id="bindData"> </div> <input type="button" id="btnPost" value="Post 點擊跨域查詢資料" /> </form> <script> $(‘#btnGet‘).bind(‘click‘, function (e) { $.ajax({ type: "GET", url: "http://localhost:20128/api/UserInfo", success: function (data) { var html = ""; $.each(data, function (index, val) { html += "<ul><li>GroupName: " + val.Id + " -- " + val.Name + "</li></ul>"; }); $("#bindData").append(html); } }); }); $(‘#btnPost‘).bind(‘click‘, function (e) { var user = { Id: ‘1‘, Name: ‘233‘ }; $.ajax({ type: "POST", contentType: ‘application/json; charset=utf-8‘, data: JSON.stringify(user), url: "http://localhost:20128/api/UserInfo", success: function (data) { //var html = ""; //$.each(data, function (index, val) { // html += "<ul><li>GroupName: " + val.Id + " -- " + val.Name + "</li></ul>"; //}); //$("#bindData").append(html); } }); }); </script></body></html>
Ajax請求在Post資料的時候,一定要加上這樣項:
contentType: ‘application/json; charset=utf-8‘,data: JSON.stringify(user),
就這樣,只是把網路上有解決方案的整理了一下,放在了一切。
asp.net web api2.0 ajax跨域解決方案