解決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運行起來服務 運行成功如下

