JSONP 跨域请求WCF
模拟建两个项目,一个WcfService,一个 Asp.Net
一、Service WCF
1、IService1.cs 注意要加上注解[WebGet()],否则客户端不能访问到
[OperationContract] [WebGet()] Stream GetData(string callback);
2、Service1.svc
注意加上[AspNetCompatibilityRequirements]注解,
返回类型以Stream 代替string,避免返回的内容带有双引号,比如若返回 "call({msg:'Hello'})",客户端就不会执行ajax里的success或者自定义的callback函数。正确的是返回不带双引号的
call({msg:'Hello'}) 这样客户端会去执行call函数。
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service1 : IService1 { public Stream GetData(string callback) { string jsCode = callback+"({msg:'Hello,I am from WCF'})"; return new MemoryStream(Encoding.UTF8.GetBytes(jsCode)); // return "call({msg:'Hello,I am from WCF'})"; } }
3、Web.config.注意高亮部分的配置 binding="webHttpBinding"
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <services> <service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior"> <!-- Service Endpoints --> <endpoint address="" binding="webHttpBinding" contract="WcfService1.IService1" behaviorConfiguration="WcfService1.EndBehavior"> </endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior name="WcfService1.Service1Behavior"> <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 --> <serviceMetadata httpGetEnabled="true"/> <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="WcfService1.EndBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration>
二、Web Ajax
<script type="text/javascript"> function getData() { var url1 = "http://localhost:6199/WebForm1.aspx?callback=?"; jQuery.getJSON(url1, function (data) { alert("执行了success 1: " + data.msg); }); var url2 = "http://localhost:6199/Service1.svc/GetData?callback=?"; $.getJSON(url2, function (data) { alert("执行了success 2: " + data.msg); }); $.ajax({ type: "get", url: "http://localhost:6199/Service1.svc/GetData", dataType: "jsonp", success: function (data) { alert("执行了success 3: " + data.msg); }, error: function (error) { alert("调用出错"); } }); $.ajax({ type: "get", url: "http://localhost:6199/Service1.svc/GetData", dataType: "jsonp", jsonpCallback: "call", success: function (data) { alert("这里不会执行!"); }, error: function (error) { alert("调用出错"); } }); } function call(data) { alert("执行了call: " + data.msg); } getData(); </script>