时间:2021-07-01 10:21:17 帮助过:19人阅读
关于AJAX调用WCF服务分为跨域和不跨域两种方式,今天咱们先介绍下不跨域下的调用方法。DEMO是在VS2008写的.
经过测试与研究,发现AJAX调用WCF服务必须满足以下条件
1.wcf的通讯方式必须使用webHttpBinding
2.必须设置
3.服务的实现必须添加标记
4.方法前面必须添加如下标记
5.ajax方法中传递的参数名称必须和wcf服务中提供的参数方法名称一致
以下是本人写的代码,标记颜色的是需要注意的地方
服务器端配置文件代码
服务器端代码
[ServiceContract] public interface IService1 { [OperationContract] string GetData(int value); [OperationContract] City GetDataUsingDataContract(City composite); [OperationContract] ListGetList(); [OperationContract] List GetListData(List list); } // 使用下面示例中说明的数据约定将复合类型添加到服务操作。 [DataContract] public class City { int seq = 0; string cityID; string ctiyName; [DataMember] public string CityID { get { return cityID; } set { cityID=value; } } [DataMember] public string CityName { get { return ctiyName; } set { ctiyName = value; } } [DataMember] public int Seq { get { return seq; } set { seq = value; } } }
实现代码
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service1 : IService1 { [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public string GetData(int value) { return string.Format("You entered: {0}", value); } #region IService1 成员 [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] public City GetDataUsingDataContract(City composite) { City c = new City(); c.CityID = composite.CityID; c.CityName = composite.CityName; c.Seq = composite.Seq; return c; } [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] public ListGetList() { List list = new List (); City cc = new City(); cc.CityID = "1"; cc.CityName="北京"; cc.Seq = 3; list.Add(cc); City cc1 = new City(); cc1.CityID = "2"; cc1.CityName = "上海"; cc1.Seq = 4; list.Add(cc1); return list; } [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] public List GetListData(List list) { return list; } #endregion }
客户端调用代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WcfServiceDemoOne.WebForm1" %>
完整实例代码代码点击此处本站下载。
希望本文所述对大家jQuery程序设计有所帮助。