转载自http://bright895.blog.163.com/blog/static/182699233201271682847261/
WCF 服务:
一、IService1.CS
/* 系统要引用System.ServiceModel.Web ServiceContract属性把此类型公开在WCF服务中 AspNetCompatibilityRequirements属性确保端点使用了WEBHTTP绑定模型.在接口的实现类上注解声明 与webconfig中的<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />配合使用 OperationContract属性把方法公开在WCF服务中 RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json 声明传进来和返回去的数据类型为Json BodyStyle = WebMessageBodyStyle.WrappedRequest 把参数包装一下,这样可以传递多个参数进来, BodyStyle=WebMessageBodyStyle.Bare 未包装格式,输出的就是纯的Json格式。要在 * */ // 注意: 如果更改此处的接口名称 "IService1",也必须更新 Web.config 中对 "IService1" 的引用。 [ServiceContract] public interface IService1 { [OperationContract] [WebGet(ResponseFormat=WebMessageFormat.Json)] string Hello(); [OperationContract] [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] string Request(int id, string title, string content); [OperationContract] [WebGet(ResponseFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Bare)] Member GetMember(int id); [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedResponse)] List<Member> GetMemberList(); [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] Product GetProduct(); [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] DataSet GetProductSet(); [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] List<Product> GetProductList(); } /// <summary> /// 此类证明不用 注解[DataContract]也可返回Json /// </summary> public class Product { string pro_no = ""; string pro_name = ""; decimal pro_price = 0; float pro_weight = 0; public string Pro_NO { get { return pro_no; } set { pro_no = value; } } public string Pro_Name { get { return pro_name; } set { pro_name = value; } } public decimal Pro_Price { get { return pro_price; } set { pro_price = value; } } public float Pro_Weight { get { return pro_weight; } set { pro_weight = value; } } } // 使用下面示例中说明的数据约定将复合类型添加到服务操作。 [DataContract] public class Member { int id=0; string name = ""; int age = 0; string birth = ""; [DataMember] public int Id { get{return id;} set{id=value;} } [DataMember] public string Name { get { return name; } set { name = value; } } [DataMember] public int Age { get { return age; } set { age = value; } } [DataMember] public string Birth { get { return birth; } set { birth = value; } } }
二、Service1.svc.cs
// 注意: 如果更改此处的类名“Service1”,也必须更新 Web.config 和关联的 .svc 文件中对“Service1”的引用。 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service1 : IService1 { public string Hello() { return "Hello WCF"; } public string Request(int id, string title, string content) { return string.Format("您输入的标题是:{0}您输入的内容是:{1}此文章的id是:{2}", title, content, id.ToString()); } public Member GetMember(int id) { List<Member> memberList = new List<Member>(); Member m1 = new Member { Id = 1, Name = "bright", Age = 24, Birth = "1989-01-01" }; Member m2 = new Member { Id = 2, Name = "a", Age = 20, Birth = "1993-01-01" }; Member m3 = new Member { Id = 3, Name = "b", Age = 21, Birth = "1992-01-01" }; Member m4 = new Member { Id = 4, Name = "c", Age = 22, Birth = "1991-01-01" }; Member m5 = new Member { Id = 5, Name = "d", Age = 23, Birth = "1990-01-01" }; memberList.Add(m1); memberList.Add(m2); memberList.Add(m3); memberList.Add(m4); memberList.Add(m5); return memberList.Where(m => m.Id == id).ToList()[0]; } public List<Member> GetMemberList() { List<Member> memberList = new List<Member>(); Member m1 = new Member { Id = 1, Name = "bright", Age = 24, Birth = "1989-01-01" }; Member m2 = new Member { Id = 2, Name = "a", Age = 20, Birth = "1993-01-01" }; Member m3 = new Member { Id = 3, Name = "b", Age = 21, Birth = "1992-01-01" }; Member m4 = new Member { Id = 4, Name = "c", Age = 22, Birth = "1991-01-01" }; Member m5 = new Member { Id = 5, Name = "d", Age = 23, Birth = "1990-01-01" }; memberList.Add(m1); memberList.Add(m2); memberList.Add(m3); memberList.Add(m4); memberList.Add(m5); return memberList; } public Product GetProduct() { Product pro1 = new Product { Pro_Name = "candy",Pro_NO="6978123456",Pro_Price=88.56M,Pro_Weight=6.8F }; return pro1; } public List<Product> GetProductList() { List<Product> proList = new List<Product>(); Product pro1 = new Product { Pro_Name = "candy1", Pro_NO = "6978123451", Pro_Price = 88.51M, Pro_Weight = 6.8F }; Product pro2 = new Product { Pro_Name = "candy2", Pro_NO = "6978123452", Pro_Price = 88.52M, Pro_Weight = 6.8F }; Product pro3 = new Product { Pro_Name = "candy3", Pro_NO = "6978123453", Pro_Price = 88.53M, Pro_Weight = 6.8F }; Product pro4 = new Product { Pro_Name = "candy4", Pro_NO = "6978123454", Pro_Price = 88.54M, Pro_Weight = 6.8F }; Product pro5 = new Product { Pro_Name = "candy5", Pro_NO = "6978123455", Pro_Price = 88.55M, Pro_Weight = 6.8F }; proList.Add(pro1); proList.Add(pro2); proList.Add(pro3); proList.Add(pro4); proList.Add(pro5); return proList; } /// <summary> /// 这样返回DataSet是不行的,得到的不是可利用的Json内容。可以将DataSet系列化成Json字符串再返回 /// </summary> /// <returns></returns> public DataSet GetProductSet() { DataSet ds = new DataSet(); DataTable dt = new DataTable(); dt.Columns.Add("Pro_Name"); dt.Columns.Add("Pro_NO"); dt.Columns.Add("Pro_Price"); dt.Columns.Add("Pro_Weight"); for (int i = 0; i < 25; i++) { DataRow dr = dt.NewRow(); dr[0] = "a"; dr[1] = "6912345678"+i; dr[2] = 8.88M+i; dr[3] = 6.8F+i; dt.Rows.Add(dr); } ds.Tables.Add(dt); return ds; } }
三、Web.config
<system.serviceModel> <services> <service name="TestWcfService.Service1" behaviorConfiguration="TestWcfService.Service1Behavior"> <!-- Service Endpoints --> <endpoint address="" binding="webHttpBinding" contract="TestWcfService.IService1" behaviorConfiguration="TestWcfService.EndBehavior"> <!-- 部署时,应删除或替换下列标识元素,以反映 在其下运行部署服务的标识。删除之后,WCF 将 自动推导相应标识。 --> <!--<identity> <dns value="localhost"/> </identity>--> </endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior name="TestWcfService.Service1Behavior"> <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点--> <serviceMetadata httpGetEnabled="true"/> <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息--> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="TestWcfService.EndBehavior"> <!--<enableWebScript/>--><!--为了输出纯的json而注释掉的--> <webHttp/> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel>
客户端Asp.net WebForm1.aspx (与WCF在同个项目下面)
<script type="text/javascript" src="jquery-1.2.6.min.js"></script> id:<input type="text" id="id" /> title:<input type="text" id="title" /> content:<input type="text" id="content" /> <input type="button" id="btn" onclick="call()" value="Submit"/> <br /> Get Single Member input member id(1~5):<input type="text" id="mid" /> <input type="button" id="Button1" onclick="getMember()" value="Submit"/> <br /> Get List: <input type="button" id="Button2" onclick="getMemberList()" value="getMemberList"/> <br /> Single Product:<input type="button" id="Button3" onclick="getProduct()" value="getProduct"/> <br /> Get Product List:<input type="button" id="Button5" onclick="getProductList()" value="getProductList"/> <br /> DataSet:<input type="button" id="Button4" onclick="getProductSet()" value="getProductSet"/> <script type="text/javascript"> $.ajax({ type:"get", url: "http://localhost:7000/Service1.svc/Hello", contentType: "application/json; charset=utf-8", success: function (json) { alert(json) }, error: function(error) { alert("调用出错" + error.responseText); } }); function call(){ var id = Number($("#id").val()); var title = String($("#title").val()); var content = String($("#content").val()); $.ajax({ type: "post", url: "http://localhost:7000/Service1.svc/Request", data: '{"id":' + id + ',"title":"' + title + '","content":"' + content + '"}', contentType: "application/json; charset=utf-8", success: function(json) { alert(json) }, error: function(error) { alert("调用出错" + error.responseText); } }); } function getMember() { var id = Number($("#mid").val()); $.ajax({ type: "get", url: "http://localhost:7000/Service1.svc/GetMember", data: {id:id}, contentType: "application/json; charset=utf-8", success: function(json) { alert(json) }, error: function(error) { alert("调用出错" + error.responseText); } }); } function getMemberList() { $.ajax({ type: "get", url: "http://localhost:7000/Service1.svc/GetMemberList", contentType: "application/json; charset=utf-8", success: function(json) { alert(json) }, error: function(error) { alert("调用出错" + error.responseText); } }); } function getProduct() { $.ajax({ type: "get", url: "http://localhost:7000/Service1.svc/GetProduct", contentType: "application/json; charset=utf-8", success: function(json) { alert(json) }, error: function(error) { alert("调用出错" + error.responseText); } }); } function getProductList() { $.ajax({ type: "get", url: "http://localhost:7000/Service1.svc/GetProductList", contentType: "application/json; charset=utf-8", success: function(json) { alert(json) }, error: function(error) { alert("调用出错" + error.responseText); } }); } function getProductSet() { $.ajax({ type: "get", url: "http://localhost:7000/Service1.svc/GetProductSet", contentType: "application/json; charset=utf-8", success: function(json) { alert(json) }, error: function(error) { alert("调用出错" + error.responseText); } }); } </script>