使用 WCF 创建 REST 服务
使用 WCF 和 VS 2010 创建简单的 REST 服务
引言
REST 代表表述性状态转移。其核心组件是资源和可以影响这些资源的动作。本文与我最初的帖子 此处 相同。
REST 动作
GET: GET is used exclusively to retrieve data.
DELETE: DELETE is used for deleting resources.
PUT: PUT is used to add or change a resource.
POST: POST is Used to modify and update a resource
WCF 与 REST
在 WCF 中,REST 应用程序最重要的元素包括 [WebGet]
和 [WebInvoke]
属性,以及与 webHttp
端点行为结合使用的新绑定 webHttpBinding
。
WebHttpBehavior
类或端点行为还允许您选择两种不同的序列化格式:
- POX(普通旧 XML)仅使用 XML,没有 SOAP 开销。
- JSON(JavaScript 对象表示法)是一种非常紧凑和高效的格式,主要与 JavaScript 配合使用。
演示
以下示例展示了如何使用 [WebGet]
和 [WebInvoke]
。
步骤 1:定义数据契约
[DataContract]
public class Student
{
[DataMember]
public string StudentName { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public double Mark { get; set; }
}
步骤 2:定义服务契约
[ServiceContract]
public interface IStudentService
{
[OperationContract]
[WebGet(UriTemplate = "/GetStudentObj")]
Student GetStudent();
[OperationContract]
[WebInvoke(UriTemplate = "/DeleteStudent/{studentName}",
Method = "DELETE")]
void DeleteStudent(string studentName);
}
步骤 3:实现服务契约
public class StudentService :
IStudentService
{
public Student GetStudent()
{
Student stdObj = new Student {
StudentName = "Foo",
Age = 29,
Mark = 95 };
return stdObj;
}
void DeleteStudent(string studentName)
{
// delete logic
}
}
步骤 4:使用 webHttpBinding(将默认 http 端口映射更改为 webHttpBinding)
<system.serviceModel>
<protocolMapping>
<add scheme="http" binding="webHttpBinding"/>
</protocolMapping>
<behaviors>
<system.serviceModel>
步骤 5:指定 webHttp 端点行为
<system.serviceModel>
-----
</protocolMapping>
<behaviors>
<endpointBehaviors>
<behavior>
<webHttp />
</behavior >
</endpointBehaviors>
<behaviors>
------
<system.serviceModel>
步骤 6:测试服务
https:///StudentService.svc/GetStudentObj
https:///StudentService.svc/DeleteStudent/foo
结论
本教程旨在帮助您理解 WCF REST 服务。希望本教程对您有所帮助和启发。