解決AJAX跨域WCF的問題詳解

解決AJAX跨域WCF的問題

公司作的網站H5和後臺分離的,只調用接口,必須解決H5跨域問題。web

網上百度沒有很詳細的, 帶附件的帖子在本身這永遠運行不起來很頭疼,而後看到一篇帖子,說的還算清楚,可是不怎麼詳細。ajax

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

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

新建完後是這樣,點開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)]app

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

每次訪問都會通過的一個全局控制器網站

 

 雙擊進去,找到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();ui

 

最後最重要的一步,咱們雙擊項目的web.config 看圖吧  博客園顯示圖下能夠右鍵另存爲,查看大圖

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

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

<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
到這就結束了~
相關文章
相關標籤/搜索