支持ajax 跨域调用的WCF搭建
1.新建一个"ASP.NET空Web应用程序"项目。
2.新建一个“WCF服务(支持ajax)”。
3.修改WCFAjaxService.svc下的WCFAjaxService.svc.cs文件
如下所示(示例):
namespace WCF_Ajax跨域调用示例 { [ServiceContract(Namespace = "WCF_Ajax跨域调用示例")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")] public class WCFAjaxService { [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] public List<UserInfo> GetUser() { return new List<UserInfo>(){ new UserInfo(){Id=1,Name="jayjay1"},new UserInfo(){Id=2,Name="jayjay2"}}; } } [DataContract] public class UserInfo { [DataMember] public int Id { get; set; }
[DataMember]
public string Name { get; set; } } }
注意别忘了给Service打上
[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]
标记。
4.修改Web.config配置文件
<system.serviceModel> <bindings> <webHttpBinding> <binding name="HttpJsonBinding" crossDomainScriptAccessEnabled="true"></binding> </webHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="AjaxServiceAspNetAjaxBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/> <services> <service name="AjaxService"> <endpoint address="" behaviorConfiguration="AjaxServiceAspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="HttpJsonBinding" contract="AjaxService" /> </service> </services> </system.serviceModel>
注意,配置文件中添加了
<bindings> <webHttpBinding> <binding name="HttpJsonBinding" crossDomainScriptAccessEnabled="true"></binding> </webHttpBinding> </bindings>
节点,并在endpoint节点中添加了
bindingConfiguration="HttpJsonBinding"
5.调用方式
在另一个网站中使用
$.ajax({ url: "http://localhost:46318/WCFAjaxService.svc/GetUser?jsoncallback=?", type: "get", dataType: "jsonp", success: function (data) { alert(data[0]); } });
调用。
从返回报文中可以看出数据以jsonp格式跨域返回。
jsonp1430098026913([{"__type":"UserInfo:#WCF_Ajax%E8%B7%A8%E5%9F%9F%E8%B0%83%E7%94%A8%E7%A4%BA%E4%BE%8B","Id":1,"Name":"jayjay1"},{"__type":"UserInfo:#WCF_Ajax%E8%B7%A8%E5%9F%9F%E8%B0%83%E7%94%A8%E7%A4%BA%E4%BE%8B","Id":2,"Name":"jayjay2"}]);
data[0]指的是取第一个json对象,如 data[0].Name取到“jayjay1” 。