通過伺服器端設定解決前端AJAX請求跨域訪問WebServie(C#開發,IIS發布)

來源:互聯網
上載者:User

標籤:網站   行修改   javascrip   節點   request   fun   head   rip   通過   

通過伺服器端設定解決前端AJAX請求跨域訪問WebServie(C#開發,IIS發布)

 

問題:前端通過ajax調用時候發生錯誤跨域訪問的錯誤

<!--功能說明:Ajax調用WebService
<script type="text/javascript">
function test(){

$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "http://www.xxxx.org/test.asmx/TestMethod",
data:"{a:12345,b:‘abcd‘}",

success: function (response) {
alert("成功:" + response.d);
},
error: function (msg) {
alert("錯誤:" + msg);
}
})

}
</script>


解決方案:在WebService服務組態檔web.config檔案中添加跨域訪問許可,共有2個地方需要修改


1、在configuration節點中的system.web節點裡面添加

<!--客服端跨域調用要使用-->
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>

表示可以支援Http的get和post訪問,可以更具需求進行修改

2、在在configuration節點中直接添加

<!--客服端跨域調用要使用-->
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
其中Access-Control-Allow-Origin的值可以依據具體情況進行設定,為“*”表示所有網站都可以訪問

通過伺服器端設定解決前端AJAX請求跨域訪問WebServie(C#開發,IIS發布)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.