服务端
1.新建空白解决方案,然后再空白解决方案中新建:WCF服务应用程序。建完后如图:
2.删掉自动生成的IService1.cs和Service.svc并添加WCF服务文件StudentService.svc,VS会自动生成IStudentService.cs 在添加一个Student类,如图:
Student.cs:
1 ///2 /// DataContract数据约定,保证student类在WCF调用中被序列化 3 /// DataMember 在被序列化的成员变量中必须加 [DataMember]标签 4 /// 5 [DataContract] 6 public class Student 7 { 8 [DataMember] 9 public string StudentId { get; set; }10 [DataMember]11 public string StudentName { get; set; }12 }
IStudentService.cs:
1 ///2 /// ServiceContract:服务约定,代表我们所能操作的接口集合,提 供功能点。 3 /// OperationContract: 每个对外需要发布的方法都需要加上此标签 4 /// 5 [ServiceContract] 6 public interface IStudentService 7 { 8 [OperationContract] 9 ListRemoveStudent(string id);10 }
StudentService.svc:
1 public class StudentService : IStudentService 2 { 3 4 public ListRemoveStudent(string id) 5 { 6 var students = new List () { 7 new Student {StudentId="1",StudentName="学生1" }, 8 new Student {StudentId="2",StudentName="学生2" } 9 };10 11 var student = students.Find(m => m.StudentId == id);12 13 students.Remove(student);14 15 return students;16 }17 }
到现在为止我们WCF服务端程序建好了,我们把StudentService.svc设为起始页,F5运行一下,会弹出来WCF测试客户端,如图
双击左侧的RemoveStudent(),在右侧输入值然后点击调用,如图:
结果如我们预料的那样,StudentId为1的数据被删掉了。
接下来我们把它部署到IIS上, 在默认文档里添加StudentService.svc,然后浏览,如图:
客户端
1.新建空白解决方案,新建ASP.NET WEB应用程序,名称为WCFClient,添加服务引用,服务引用地址为上图地址中的
,如图:
WCFTest.aspx:
1
WCFTest.aspx.cs:
1 protected void btnSubmint_OnClick(object sender, EventArgs e) 2 { 3 var wcfService = new WCFService.StudentServiceClient(); 4 5 var str = string.Empty; 6 7 wcfService.RemoveStudent(this.txtStudentId.Text.Trim()) 8 .ToList() 9 .ForEach(m =>str += m.StudentId + ":" + m.StudentName);10 11 Response.Write(str);12 }
运行下,看下效果: