可以更具需求进行修改 2、在在configuration节点中直接添加 !--客服端跨域调用要使用-- system.w

时间:2022-06-04 08:51:01

通过处事器端设置解决前端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/>
<add/>
</protocols>
</webServices>

暗示可以撑持Http的get和post访谒,可以更具需求进行改削

2、在在configuration节点中直接添加

<!--客服端跨域挪用要使用-->
<system.webServer>
<httpProtocol>
<customHeaders>
<add value="OPTIONS,POST,GET"/>
<add value="x-requested-with,content-type"/>
<add value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
此中Access-Control-Allow-Origin的值可以依据具体情况进行设定,为“*”暗示所有网站都可以访谒