解决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运行起来服务 运行成功如下

                    
                
                
            
        
浙公网安备 33010602011771号