跨越問題主要發生在客戶端ajax請求時,爲了安全設置,默認webapi是不容許ajax跨越請求的,不過有方法設置讓支持跨越,我說說最多見的兩種方法javascript
缺點:JSONP也有侷限性,只能針對於Get請求不能用於POST請求html
一、新建過濾器java
Filters/JsonCallbackAttribute.csjquery
using System.Net.Http; using System.Text; using System.Web.Http.Filters; namespace cms.Web { public class JsonCallbackAttribute : ActionFilterAttribute { private const string CallbackQueryParameter = "jsoncallback"; public override void OnActionExecuted(HttpActionExecutedContext context) { var callback = string.Empty; if (IsJsonp(out callback)) { var jsonBuilder = new StringBuilder(callback); jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result); context.Response.Content = new StringContent(jsonBuilder.ToString()); } base.OnActionExecuted(context); } private bool IsJsonp(out string callback) { callback = System.Web.HttpContext.Current.Request.QueryString[CallbackQueryParameter]; return !string.IsNullOrEmpty(callback); } } }
二、Global.asax註冊web
protected void Application_Start() { GlobalConfiguration.Configuration.Filters.Add(new JsonCallbackAttribute());//讓webapi支持jsonp跨越請求 }
三、webapiajax
api方法地址:www.ceshi1.com/api/ceshi/getceshijson
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.Results; using cms.BLL; using cms.Model; namespace cms.Web.API { public class CeshiController : ApiController { public IHttpActionResult GetCeshi() { dynamic data = new { status = true, message = "webapi success" }; return Json<dynamic>(data); } } }
四、ceshi.htmlapi
訪問地址:www.ceshi2.com/ceshi.html跨域
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ceshi3.aspx.cs" Inherits="ceshi3" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript" src="/js/jquery.js"></script> </head> <body> 測試結果1:<span id="test" style="color:Red"></span><br /> 測試結果2:<span id="test2" style="color:Red"></span> <script type="text/javascript"> function success_jsonpCallback(data) { alert(data) } $(function () { $.getJSON("http://www.ceshi1.com/api/ceshi/Getceshi?jsoncallback=?", function (data) { $("#test").html(data.message); } ); $.ajax({ type: "get", url: "http://www.ceshi1.com/api/ceshi/Getceshi", dataType: "jsonp", jsonp: "jsoncallback", //async: false, success: function (data) { $("#test2").html(data.message); }, error: function (e) { $("#test2").html("Error"); } }); }); </script> </body> </html>
CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)。
它容許瀏覽器向跨源服務器,發出XMLHttpRequest請求,從而克服了AJAX只能同源使用的限制。瀏覽器
推薦使用這個解決跨越問題
一、安裝webapi.cors
二、配置WebApiConfig
using System; using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace WebApi { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服務 //設置cors容許跨越 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
三、webapi
api方法地址:www.ceshi1.com/api/ceshi/getceshi
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace WebApi.Controllers { //自定義cors //[EnableCors(origins: "http://www.ceshi2.com", headers: "*", methods: "*")] //[EnableCors(origins: "http://www.example.com", headers: "*", methods: "get,post")] public class CeshiController : ApiController { public IHttpActionResult GetCeshi() { dynamic data = new { status = true, message = "webapi success" }; return Json<dynamic>(data); } } }
四、ceshi.html
訪問地址:www.ceshi2.com/ceshi.html
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ceshi3.aspx.cs" Inherits="ceshi3" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript" src="/js/jquery.js"></script> </head> <body> 測試結果1:<span id="test" style="color:Red"></span><br /> 測試結果2:<span id="test2" style="color:Red"></span> <script type="text/javascript"> $(function () { $.get("http://1.ceshi.com/api/ceshi/Getceshi", function (data) { $("#test").html(data.message); } ); jQuery.support.cors = true;//必須,否則ie八、ie9不支持跨越 $.ajax({ type: "get", url: "http://1.ceshi.com/api/ceshi/Getceshi", //dataType: "json", success: function (data) { $("#test2").html(data.message); }, error: function (e) { $("#test2").html("Error"); } }); }); </script> </body> </html>
說明:cors設置後ajax就和普通寫法同樣調用了
注意:剛開始個人webapi和mvc在一個項目中,設置cors不起做用,不知道爲什麼。而後把webapi單獨一個項目卻能夠,坑死我了。
end