REST WCF 4.0 新特性简介

  前面几节介绍了REST WCF 3.5的一些基本特性以及使用方式,在WCF4.0的时代,也做了对REST的支持。相比3.5时代,4.0改进体现有如下几点:

  1. 增加对路由的支持
  2. 对缓存的支持。
  3. 帮助(help)页面的改进。
  4. 消息错误处理
  5. 消息格式的多样性如(XML\JSON\ATOM\TEXT\BINARY)
  6. 简化操作。

  本节讲述的重点为如何使用路由注册REST服务、缓存以及help页面
  1、使用路由注册服务。
  WCF4.0中新增的路由服务可以帮助直接注册服务,而不再需要SVC的文件。
  需要注意的是,使用路由注册服务时必须启动ASP.NET的兼容模式。即设置aspNetCompatibilityEnabled=True,并且相应的提供服务接口的类。需要将AspNetCompatibilityRequirements 特性添加到服务类型且同时RequirementsMode 设置为“Allowed”或“Required”。否则服务无法使用。启动ASP.NET的兼容模式,可使用ASP.NET的一些特性。
  REST WCF即WCF的WEB编程模型中,我们使用的是WebServiceHost,它是ServiceHost(当您没有使用 Internet 信息服务 (IIS) 或 Windows 激活服务 (WAS) 公开服务时,请使用 ServiceHost 类来配置和公开服务以供客户端应用程序使用)的派生类。如果REST WCF没有指定服务终结点地址,WebServiceHost会在服务的基址中自动为 HTTP 和 HTTPS 基址创建一个默认终结点。如果用户指明了服务的终结点地址,则它不会创建。
WebServiceHostFactory在可动态创建WebServiceHost Web宿主实例以响应传入消息的托管宿主环境中提供 WebServiceHost 的实例的工厂。
而采用路由注册服务时,使用的就是WebServiceHostFactory。如下图:

 

代码如下:

private void RegisterRoutes()
{
WebServiceHostFactory webServiceHostFactory = new WebServiceHostFactory();
RouteTable.Routes.Add(new ServiceRoute("Service",
webServiceHostFactory, typeof(Services)));
}

  如图示:"Service"为Services类中提供服务的别名。它指明了Web地址的相对URI。使用服务的时候。它是ServiceRoute构造时必须的。

2、缓存
REST WCF中,同样可以通过如同ASP.NET配置缓存的方式来配置服务接口的缓存。如在web.config文件中做如下配置:

<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="RestCahe10" duration="10" varyByParam=""/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>

[WebGet(UriTemplate ="/")]
[AspNetCacheProfile("RestCahe10")]
public DateTime GetTime()
{
return DateTime.Now ;
}

  

注意:varyByParam在缓存设置中是必须有的。
3、帮助页面
在REST 服务中,已经没有了WSDL文档可以供调用者使用。于是,REST中,通过帮助页告知调用者如何使用服务。在F3.5时代,REST WC
就支持帮助页,在4.0中,有了进一步的改进。
启用帮助页有两种方式。
1、通过在<endpointBehavior>节点的<behavior>设置。如下:

<behaviors>
<endpointBehaviors>
<behavior>
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>

  


2、通过新增的standardEndpoints节点进行配置。如下:

<standardEndpoints>
<webHttpEndpoint>
--><!-- 
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
via the attributes on the <standardEndpoint> element below
--><!--
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>

  帮助页面如下:

点击相应的方法进去后,会详细显示,此方法所使用的HTTP动作,请求、响应等等信息。如下图:

posted @ 2011-11-16 17:35  tyb1222  阅读(2760)  评论(2编辑  收藏  举报