解決AJAX跨域WCF的問題詳解


解決AJAX跨域WCF的問題

公司做的網站H5和后台分離的,只調用接口,必須解決H5跨域問題。

網上百度沒有很詳細的, 帶附件的帖子在自己這永遠運行不起來很頭疼,然后看到一篇帖子,說的還算清楚,但是不怎么詳細。

本次事列使用VS2015  Framework4.5.2 演示

首先我們新建一個項目,常規的wcf項目

新建完后是這樣,點開Service1.svc

在實現類上加入下面三句,如圖

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

在進入接口類,在要實現跨域的Action上加入下面這句

        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]

 右鍵項目新建一個項,全局Global.asax

每次訪問都會經過的一個全局控制器

 

 雙擊進去,找到Application_BeginRequest方法添加如下

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod != "OPTIONS") return;
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();

 

最后最重要的一步,我們雙擊項目的web.config 看圖吧  博客園顯示圖下可以右鍵另存為,查看大圖

兩端配置
<!--ajax跨域配置-->
<endpointBehaviors>
<behavior name="AjaxServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
<!--ajax跨域配置-->

<!--ajax跨域配置-->

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="RivValleyService.RValleyService">
<endpoint address="" behaviorConfiguration="AjaxServiceAspNetAjaxBehavior"
binding="webHttpBinding" bindingConfiguration="HttpJsonBinding" contract="RivValleyService.IRValleyService" />
</service>
</services>
<bindings>

<!--ajax跨域配置-->

 

 

然后我雙擊Service1運行起來服務  運行成功如下

 

 前台調用,輸入你的IP和端口  url一定要對,    方法名GetData后要接上  ?jsoncallback=?  否則將無法跨域

$.ajax({
url: "http://localhost:55147/RValleyService.svc/GetData?jsoncallback=?",
type: "get",
data:{value:111},
dataType: "jsonp",
success: function (data) {
alert(data);
}
});
});
OK
到這就結束了~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM