解决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
到这就结束了~
相关文章
相关标签/搜索