在Silverlight中使用基于WCF的REST服务PartI

创建基于WCF的RESTful服务

必要的准备

为了实现一个常用的REST服务场景,就必须首先搭建一个必要的舞台:

其中包括以下几个实体:

  • User,用户
  • Post,用户发布的文章
  • Comments,文章的评论

同时对外提供以下的服务:

  • GetAllUsers(),获取所有的用户信息
  • GetPostsByName(),按照用户名称获取其发布的所有文章信息
  • GetPostByID(),按照文章ID获取该篇文章信息
  • GetCommentByAuthor(),按照评论者姓名获取其评论信息
  • AddComment(),添加按照文章添加评论

详细的情况,我们将在后文的创建过程中逐层解开。

WCF的REST基础

.NET 3.5中实现了WCF的扩展从而可以在SOAP和REST中作出更多的选择,我们在了解REST的基础上就可以轻而易举的对WCF的REST支持有个快速的认知。首先,值得关注的是WCF中一系列重要的支持框架,需要重点关注的是:

  • WebGetAttribute和WebInvokeAttribute,其中WebGet标识调度程序响应HTTP GET请求,而WebInvoke则标示调度程序响应任何HTTP请求,其中以WebInokeAttribute.Method属性来标识,默认情况下 映射为HTTP POST。以WebGet为例,
[AttributeUsage(AttributeTargets.Method)]
public sealed class WebGetAttribute : Attribute, IOperationBehavior, IWmiInstanceProvider
{
public WebGetAttribute();
public WebMessageBodyStyle BodyStyle { get; set; }
public bool IsBodyStyleSetExplicitly { get; }
public bool IsRequestFormatSetExplicitly { get; }
public bool IsResponseFormatSetExplicitly { get; }
public WebMessageFormat RequestFormat { get; set; }
public WebMessageFormat ResponseFormat { get; set; }
public string UriTemplate { get; set; }
}

其中UriTemplate是WCF为每种资源以模板的方式定义URI,使用方法和动词的组合,例如:

[WebInvoke(UriTemplate = "/{name}/{post}", Method = "POST")]
Comment AddComment(string name, string post, Comment comment);

RequestFormat和ResponseFormat是WebMessageFormat类型的成员,其表示了Request和Response过程的传输格式为Xml或者Json:

public enum WebMessageFormat
{
Xml = 0,
Json = 1,
}

那么,按照WCF REST定义语法,我们开始定义一个完整的IPostService Contract如下:

// Release : 2009/02/12                            
// Author : Anytao, http://www.anytao.com
[ServiceContract(Namespace="http://api.anytao.com/rest/")]
public interface IPostService
{
[OperationContract]
[WebGet(UriTemplate = "/", ResponseFormat = WebMessageFormat.Xml)]
List<User> GetAllUsers();

[OperationContract]
[WebGet(UriTemplate = "/{name}", ResponseFormat = WebMessageFormat.Xml)]
List<Post> GetPostsByName(string name);

[OperationContract]
[WebGet(UriTemplate = "/{name}/{post}", ResponseFormat = WebMessageFormat.Json)]
Post GetPostByID(string name, string post);

[OperationContract]
[WebGet(UriTemplate = "/{name}/{post}/{comment}", ResponseFormat = WebMessageFormat.Json)]
Comment GetCommentByAuthor(string name, string post, string comment);

[OperationContract]
[WebInvoke(UriTemplate = "/{name}/{post}", Method = "POST")]
Comment AddComment(string name, string post, Comment comment);
}
  • WebHttpBinding和WebHttpBehavior,就像BasicHttpBinding和BasicHttpBehavior一 样,用于确定WCF的通信方式,WebHttpBinding用于为通过HTTP请求公开的WCF服务配置终结点,WebHttpBehavior则完成 对于“URI+谓词”的启动,为WebHttpBinding支持Web样式服务提供支持。像一般的WCF服务一样,WebHttpBinding可以通 过编码方式和配置方式两种途径完成,当然我们更推荐的是配置方式:
  <bindings>
<
webHttpBinding>
<
binding name="secure">
<
security mode="Transport">
<
transport clientCredentialType="Basic"/>
</
security>
</
binding>
</
webHttpBinding>
</
bindings>
<
behaviors>
<
endpointBehaviors>
<
behavior name="postbehavior">
<
webHttp/>
</
behavior>
</
endpointBehaviors>
</
behaviors>
  • WebServiceHost和WebServiceHostingFactory,顾名思义WebServiceHost承载利用配置终结点的 绑定,而WebServiceHostingFactory利用工厂模式进行WebServiceHost的创建工作。在Self Host时,我们可以利用WebServiceHost简化对WebHttpBinding和WebHttpBehavior的配置过程,例如:
// Release : 2009/02/19                            
// Author : Anytao, http://www.anytao.com
static void Main(string[] args)
{
string baseUri = "http://localhost:6666/PostService";
WebServiceHost sh = new WebServiceHost(typeof(PostService),
new Uri(baseUri));

sh.Opened += (s1,s2) =>
{
Console.WriteLine("Service begin to listen via {0}", baseUri);
};

sh.Open();
Console.ReadLine();
}

我们将在下面的创建过程中逐步接触这些概念及其应用。

Note:下面是WCF REST的有用资源:WCF REST Starter Kit 

实现WCF的REST服务

实现WCF的REST服务和一般的WCF服务并无二致,都是通过实现契约接口,对提供的服务进行具体实现,限于篇幅我们仅将GetPostByName服务做以举例:


// Release : 2009/02/19                            
// Author : Anytao, http://www.anytao.com
public class PostService : IPostService
{
private List<User> users;

public List<Post> GetPostsByName(string name)
{
User user = (from u in users
where u.Name == name
select u).Single();

return user.Posts;
}
}
共有0个回答