实现契约接口
创建类库项目WcfService.Implementation,添加对WcfService.Contract的引用。通过EmployeeService类,继承和实现IEmployeeService中定义的契约服务接口。代码大致如下:
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Net;
using System.ServiceModel.Activation;
using WcfService.Contract;
namespace WcfService.Implementation
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class EmployeeService : IEmployeeService
{
private static List<Employee> employees = new List<Employee>
{
new Employee{ Id = "001", Name="万事通", Department="开发部", Grade = "G4"},
new Employee{ Id = "002", Name="害羞鬼", Department="人事部", Grade = "G6"},
......
};
public Employee GetEmployeeById(string id)
{
Employee employee = employees.FirstOrDefault(e => e.Id == id);
if (null == employee)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
}
return employee;
}
public IEnumerable<Employee> GetAllEmployees()
{
return employees;
}
public void AddEmployee(Employee employee)
{
......
}
public void UpdateEmployee(Employee employee)
{
......
}
public void DeleteEmployee(string id)
{
.......
}
}
}
在EmployeeService类中,我们定义了一个Employee的List集合,用来存放Employee对象,以模拟实际应用中的数据对象的存取操作。前文契约中定义的HTTP协议的GET、POST、PUT、DELETE实际动作,将对应与EmployeeService类中对接口实现的具体功能。WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
GetEmployeeById(string id)方法中的上述代码,指定了如果要获取的对象不存在时,当前WCF上下文应该返回的状态值。
查看项目WcfService.Implementation中的代码文件EmployeeService.cs,找出方法实现所对应的CURD动作,并编译项目生成相应的实现类库。