Welcome

首页 / 软件开发 / WCF / Learn WCF (2)--开发WCF服务

Learn WCF (2)--开发WCF服务2010-09-10 博客园 GWPBrian在上一篇中和大家复习了有关WCF的一些基础知识,这篇通过实例和大家分享如何开发一个获取,添加学生信息的WCF服务。

开发WCF服务的端点需要涉及下面几个任务:

开发服务契约:指定端点可用的WCF服务的操作。

开发绑定:绑定指点端点与外界通信的协议。

添加,删除,更新和配置端点:在配置文件中添加和绑定端点(当然也可以用编码的形式,但是不推荐。)

添加行为:一个行为就是一个组件,能增强服务,端点,和操作的运行时行为。

开发一个WCF服务契约

一个WCF服务契约是一个用元数据属性[ServiceContract]修饰的.NET接口或类。每个WCF服务可以有一个或多个契约,每个契约是一个操作集合。

首先我们定义一个.NET接口:IStuServiceContract,定义两个方法分别实现添加和获取学生信息的功能

void AddStudent(Student stu);stuCollection GetStudent();

用WCF服务模型的元数据属性ServiceContract标注接口IStuServiceContract,把接口设计为WCF契约。用OperationContract标注AddStudent,GetStudent

GetStudent()返回一个类型为stuCollection类型的集合。AddStudent()需要传入Student实体类作为参数。

namespace WCFStudent
{
[ServiceContract]
public interface IStuServiceContract
{

[OperationContract]
void AddStudent(Student stu);

[OperationContract]
stuCollection GetStudent();

}

[DataContract]
public class Student
{
private string _stuName;
private string _stuSex;
private string _stuSchool;

[DataMember]
public string StuName
{
get { return _stuName; }
set { _stuName = value; }
}

[DataMember]
public string StuSex
{
get { return _stuSex; }
set { _stuSex = value; }
}

[DataMember]
public string StuSchool
{
get { return _stuSchool; }
set { _stuSchool = value; }
}
}

public class stuCollection : List<Student>
{

}
}

WCF服务和客户交换SOAP信息。在发送端必须把WCF服务和客户交互的数据串行化为XML并在接收端把XML反串行化。因此客户传递给AddStudent操作的Student对象也必须在发送到服务器之前串行化为XML。WCF默认使用的是一个XML串行化器DataContractSerializer,用它对WCF服务和客户交换的数据进行串行化和反串行化。

作为开发人员,我们必须要做的是用元数据属性DataContract标注WCF和其客户所交换的数据的类型。用元数据属性DataMember标注交换数据类型中要串行化的属性。(详细看上面的代码)