Restful WCF开发实践 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

定义服务契约

定义服务契约IEmployeeService,对外提供服务操作功能,以对应REST服务的CURD操作:

  • IEnumerable GetAllEmployees() 获取所有的员工对象
  • Employee GetEmployeeById(string id) 由id获取指定的员工
  • void AddEmployee(Employee employee) 增加一个员工对象
  • void UpdateEmployee(Employee employee) 更改一个员工对象信息
  • void DeleteEmployee(string id) 删除id指定的员工

Restful WCF的服务契约定义例子代码如下:

[ServiceContract]
public interface IEmployeeService
{
    [OperationContract]
    [WebGet(UriTemplate = "employee/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Employee GetEmployeeById(string id);  

    [OperationContract]
    [WebGet(UriTemplate = "employees", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    IEnumerable<Employee> GetAllEmployees();

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "employee", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    void AddEmployee(Employee employee);

    [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "employee", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    void UpdateEmployee(Employee employee);

    [OperationContract]
    [WebInvoke(Method = "DELETE", UriTemplate = "employee/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    void DeleteEmployee(string id);  

}

代码中通过[ServiceContract][OperationContract]两个Attribute来标记接口类和方法,来告诉编译器这是服务契约和操作契约。

查看项目WcfService.Contract中的代码文件IEmployeeService.cs,学习数据契约和服务契约定义的格式,编译项目生成相应的契约类库。