前言:上篇總結了下webapi的接口測試工具的使用,這篇接著來看看webapi的另一個常見問題:跨域問題。本篇主要從實例的角度分享下cors解決跨域問題一些細節。
一、跨域問題的由來
同源策略:出于安全考慮,瀏覽器會限制腳本中發起的跨站請求,瀏覽器要求javascript或cookie只能訪問同域下的內容。
正是由于這個原因,我們不同項目之間的調用就會被瀏覽器阻止。比如我們最常見的場景:webapi作為數據服務層,它是一個單獨的項目,我們的mvc項目作為web的顯示層,這個時候我們的mvc里面就需要調用webapi里面的接口取數據展現在頁面上。因為我們的webapi和mvc是兩個不同的項目,所以運行起來之后就存在上面說的跨域的問題。
二、跨域問題解決原理
cors全稱cross-origin resource sharing,中文全稱跨域資源共享。它解決跨域問題的原理是通過向http的請求報文和響應報文里面加入相應的標識告訴瀏覽器它能訪問哪些域名的請求。比如我們向響應報文里面增加這個access-control-allow-origin:http://localhost:8081,就表示支持http://localhost:8081里面的所有請求訪問系統資源。其他更多的應用我們就不一一列舉,可以去網上找找。
三、跨域問題解決細節
下面我就結合一個簡單的實例來說明下如何使用cors解決webapi的跨域問題。
1、場景描述
我們新建兩個項目,一個webapi項目(下圖中webapicors),一個mvc項目(下圖中web)。webapi項目負責提供接口服務,mvc項目負責頁面呈現。如下:
其中,web與webapicors端口號分別為“27239”和“27221”。web項目需要從webapicorss項目里面取數據,很顯然,兩個項目端口不同,所以并不同源,如果使用常規的調用方法肯定存在一個跨域的問題。
簡單介紹下測試代碼,web里面有一個homecontroller
1
2
3
4
5
6
7
8
|
public class homecontroller : controller { // get: home public actionresult index() { return view(); } } |
對應的index.cshtml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
< html > < head > < meta name = "viewport" content = "width=device-width" /> < title >index</ title > < script src = "~/content/jquery-1.9.1.js" ></ script > < link href = "~/content/bootstrap/css/bootstrap.css" rel = "external nofollow" rel = "stylesheet" /> < script src = "~/content/bootstrap/js/bootstrap.js" ></ script > < script src = "~/scripts/home/index.js" ></ script > </ head > < body > 測試結果:< div id = "div_test" > </ div > </ body > </ html > |
index.js文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
var apiurl = "http://localhost:27221/" ; $( function () { $.ajax({ type: "get" , url: apiurl + "api/charging/getallchargingdata" , data: {}, success: function (data, status) { if (status == "success" ) { $( "#div_test" ).html(data); } }, error: function (e) { $( "#div_test" ).html( "error" ); }, complete: function () { } }); }); |
webapicors項目里面有一個測試的webapi服務chargingcontroller
1
2
3
4
5
6
7
8
9
10
11
12
|
public class chargingcontroller : apicontroller { /// <summary> /// 得到所有數據 /// </summary> /// <returns>返回數據</returns> [httpget] public string getallchargingdata() { return "success" ; } } |
配置webapi的路由規則為通過action調用。webapiconfig.cs文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public static class webapiconfig { public static void register(httpconfiguration config) { // web api 路由 config.maphttpattributeroutes(); config.routes.maphttproute( name: "defaultapi" , routetemplate: "api/{controller}/{action}/{id}" , defaults: new { id = routeparameter.optional } ); } } |
2、場景測試
1)我們不做任何的處理,直接將兩個項目運行起來。看效果如何
ie瀏覽器:
谷歌瀏覽器:
這個結果另博主也很吃驚,不做任何跨域處理,ie10、ie11竟然可以直接請求數據成功,而同樣的代碼ie8、ie9、谷歌瀏覽器卻不能跨域訪問。此原因有待查找,應該是微軟動了什么手腳。
2)使用cors跨域
首先介紹下cors如何使用,在webapicors項目上面使用nuget搜索“microsoft.aspnet.webapi.cors”,安裝第一個
然后在app_start文件夾下面的webapiconfig.cs文件夾配置跨域
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public static class webapiconfig { public static void register(httpconfiguration config) { //跨域配置 config.enablecors( new enablecorsattribute( "*" , "*" , "*" )); // web api 路由 config.maphttpattributeroutes(); config.routes.maphttproute( name: "defaultapi" , routetemplate: "api/{controller}/{action}/{id}" , defaults: new { id = routeparameter.optional } ); } } |
我們暫定三個“*”號,當然,在項目中使用的時候一般需要指定對哪個域名可以跨域、跨域的操作有哪些等等。這個在下面介紹。
ie10、ie11
谷歌瀏覽器
ie8、ie9
這個時候又有新問題了,怎么回事呢?我都已經設置跨域了呀,怎么ie8、9還是不行呢?這個時候就有必要說說cors的瀏覽器支持問題了。網上到處都能搜到這張圖:
上圖描述了cors的瀏覽器支持情況,可以看到ie8、9是部分支持的。網上說的解決方案都是internet explorer 8、9使用 xdomainrequest對象實現cors。是不是有這么復雜?于是博主各種百度尋找解決方案。最后發現在調用處指定jquery.support.cors = true;這一句就能解決ie8、9的問題了。具體是在index.js里面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
jquery.support.cors = true ; var apiurl = "http://localhost:27221/" ; $( function () { $.ajax({ type: "get" , url: apiurl + "api/charging/getallchargingdata" , data: {}, success: function (data, status) { if (status == "success" ) { $( "#div_test" ).html(data); } }, error: function (e) { $( "#div_test" ).html( "error" ); }, complete: function () { } }); }); |
這句話的意思就是指定瀏覽器支持跨域。原來ie9以上版本的瀏覽器、谷歌、火狐等都默認支持跨域,而ie8、9卻默認不支持跨域,需要我們指定一下。你可以在你的瀏覽器里面打印jquery.support.cors看看。這樣設置之后是否能解決問題呢?我們來看效果:
問題完美解決。至于網上說的cors對ie8、9的解決方案xdomainrequest是怎么回事,有待實例驗證。
3)cors的具體參數設置。
上文我們使用
1
|
config.enablecors( new enablecorsattribute( "*" , "*" , "*" )); |
這一句解決了跨域問題,上面說了,這種*號是不安全的。因為它表示只要別人知道了你的請求url,任何請求都可以訪問到你的資源。這是相當危險的。所以需要我們做一些配置,限制訪問權限。比如我們比較常見的做法如下:
配置方法一、在web.config里面
然后在webapiconfig.cs文件的register方法里面
配置方法二、如果你只想對某一些api做跨域,可以直接在api的類上面使用特性標注即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
[enablecors(origins: "http://localhost:8081/" , headers: "*" , methods: "get,post,put,delete" )] public class chargingcontroller : apicontroller { /// <summary> /// 得到所有數據 /// </summary> /// <returns>返回數據</returns> [httpget] public string getallchargingdata() { return "success" ; } } |
四、總結
以上就是一個簡單的cors解決webapi跨域問題的實例,由于博主使用webapi的時間并不長,所以很多理論觀點未必成熟,如果有說的不對的,歡迎指出。也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/landeanfen/p/5177176.html