解决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
到这就结束了~

转载于:https://www.cnblogs.com/jooucks/p/7159147.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值