共同学习了前面一些概念,终于开始正题了哈。RESTful的Web Service调用直观,返回的内容容易解析。这里先会描述一个简单的场景--Web Service提供一个方法来搜索个人信息,传入人名,返回完整个人信息。
下面我们一步步用WCF实现一个RESTful的Web Service。在这之后分别描述用普通Console程序host在本地,以及用IIS发布到网络。

1. Contract

namespace WcfRESTful
{
[ServiceContract]
public interface IPersonRetriever
{
[OperationContract]
[WebGet(UriTemplate = "Persons/{name}", ResponseFormat = WebMessageFormat.Json)]
Person GetPerson(string name);
} [DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public DateTime Birthday { get; set; }
}
}

这里需要注意的是在方法GetPerson()上面的WebGetAttribute:
1.1 WebGetAttribute定义了该方法的访问方式为RESTful的Get(关于RESTful可以参考本小博中关于REST介绍的文章)。
1.2 UriTemplet描述了URL匹配的格式,当格式匹配时,{name}位置的字符串会被对应传入为方法参数。
1.3 ResponseFormat指定了返回的数据格式,可选项为JSON和XML。

2. Contract实现

namespace WcfRESTful
{
public class PersonRetriever : IPersonRetriever
{
public Person GetPerson(string name)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
return new Person { Name = name, Age = 22, Birthday = DateTime.Now };
}
}
}

这个实现里面,我们简单的返回一个用传入名参数为name的Person实例。这里补充一点:如果ContectType是"Text",如果返回结果串包含特别字符(比如转义,双引号,XML文件片段等),有些情况会在IE中解析不正常,造成字段缺失,目前没有找到相关资料说明IE解析规则。为了方便和谨慎起见,直接用"text/plain"。

3. 在Console中Host Service

在第1,2步的基础上,我们开始在console中host这个service。

namespace WcfRESTful
{
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://127.0.0.1:9998/PersonRetriever");
using (ServiceHost host = new ServiceHost(typeof(PersonRetriever), baseAddress))
{
WebHttpBinding binding = new WebHttpBinding();
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IPersonRetriever), binding, baseAddress);
WebHttpBehavior httpBehavior = new WebHttpBehavior();
endpoint.Behaviors.Add(httpBehavior);
host.Opened += delegate
{
Console.WriteLine("Hosted successfully.");
};
host.Open();
Console.ReadLine();
}
}
}
}

让后我们通过URL:http://127.0.0.1:9998/PersonRetriever/Persons/Tom 就可以访问该Service了,其中"Tom"是需要查询的人名。在IE中输入该URL,回车之后的结果如下图:

4. 在IIS中Host Web Service

4.1新建一个WCF Service(或者Web Service依.Net Framework版本不同而定)工程,把第1,2步的Contract和实现Copy到App_Code文件夹下面。

4.2修改Service.svc - 注意,Factory="System.ServiceModel.Activation.WebServiceHostFactory"必须添加才可以直接在IE查看结果,但是Matedata将被屏蔽不能显示。

<%@ ServiceHost Language="C#" Debug="true" Service="WcfRESTful.PersonRetriever" CodeBehind="~/App_Code/PersonRetriever.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>

4.3添加Endpoint到Web.config

    <system.serviceModel>
<services>
<service name="WcfRESTful.PersonRetriever" behaviorConfiguration="ServiceBehavior">
<endpoint binding="webHttpBinding" contract="WcfRESTful.IPersonRetriever"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

4.4添加工程目录到IIS虚拟路径,命名为WCFTest。

以上4.1-4.4的所有步骤都完成了,我们通过URL:http://16X.19X.18X.6X/wcftest/Service.svc/Persons/Tom 一样可以得到上面的结果{"Age":22,"Birthday":"\/Date(1329226087212-0500)\/","Name":"Tom"}。

这里需要补充一点,在4.1步骤,我们新建一个Web Service工程,仅仅是为了少写一些Web.Config的配置(会默认有system.web,complier等配置信息),其实我们完全可以新建App_Code文件夹,把Contact和Contract实现拷入该文件夹,然后在外层手工新建Service.svc,Web.config并写入相应配内容,一样可以成功部署和使用。

5. 总结
RESTful Web Service用更简单通用的协议(HTTP,少了SOAP这一道封装和解析),更直接的结果,让人眼前一亮,在资源不需要交互逻辑和复杂结构的情况下还是不错的选择。

http://www.cnblogs.com/KeithWang/archive/2012/02/14/2351826.html

WCF实现RESTFul Web Service的更多相关文章

  1. WCF 、Web API 、 WCF REST 和 Web Service 的区别

    WCF .Web API . WCF REST 和 Web Service 的区别 The .Net framework has a number of technologies that allow ...

  2. 转 Difference between WCF and Web API and WCF REST and Web Service

    http://www.dotnet-tricks.com/Tutorial/webapi/JI2X050413-Difference-between-WCF-and-Web-API-and-WCF-R ...

  3. WCF、Web API、WCF REST、Web Service

    WCF.Web API.WCF REST.Web Service 区别 Web Service It is based on SOAP and return data in XML form. It ...

  4. WCF、Web API、WCF REST、Web Service的区别

    Difference between WCF and Web API and WCF REST and Web Service   The .Net framework has a number of ...

  5. 【转】基于CXF Java 搭建Web Service (Restful Web Service与基于SOAP的Web Service混合方案)

    转载:http://www.cnblogs.com/windwithlife/archive/2013/03/03/2942157.html 一,选择一个合适的,Web开发环境: 我选择的是Eclip ...

  6. 【转】 Build a RESTful Web service using Jersey and Apache Tomcat 2009

    Build a RESTful Web service using Jersey and Apache Tomcat Yi Ming Huang with Dong Fei Wu, Qing GuoP ...

  7. Building a RESTful Web Service Using Spring Boot In Eclipse

    一.构建restful web service 创建Maven的java web工程,maven的pom文件加入依赖包 创建包hello Greeting.java package hello; pu ...

  8. 使用Java创建RESTful Web Service

    REST是REpresentational State Transfer的缩写(一般中文翻译为表述性状态转移).2000年Roy Fielding博士在他的博士论文“Architectural Sty ...

  9. (转)接口自动化测试 – Java+TestNG 测试 Restful Web Service

    本文主要介绍如何用Java针对Restful web service 做接口自动化测试(数据驱动),相比UI自动化,接口自动化稳定性可靠性高,实施难易程度低,做自动化性价比高.所用到的工具或类库有 T ...

随机推荐

  1. jdbc框架有很多,包括spring jdbc

    1.由于jdbc连接的繁琐性,故很多公司封装了jdbc框架,比如spring jdbc 2.比如spring jdbc框架中,用jdbctemplate, 通过jdbcTemplate 提供 int ...

  2. 单击行,自己主动选中当前行中的单选框button

    需求:单击行,自己主动选中当前行中的单选框button. aspx页面: <asp:Repeater ID="rptRecordList" runat="serve ...

  3. apache kafka监控系列-KafkaOffsetMonitor(转)

    原文链接:apache kafka监控系列-KafkaOffsetMonitor 概览 最 近kafka server消息服务上线了,基于jmx指标参数也写到zabbix中了,但总觉得缺少点什么东西, ...

  4. 创建一个简单的windows服务,每间隔一定时间重复执行批处理文件

    创建一个windows服务项目,增加App.config <?xml version="1.0" encoding="utf-8" ?> <c ...

  5. QT 异步函数转为同步函数的方法

    在QT中,一般推荐使用异步函数.除了异步函数的非阻塞特性外,QT的Signal/Slot特性在异步函数中可以得到充分的发挥.因此,在QT中,很多API的设计都是使用非阻塞的异步函数作为API,然后执行 ...

  6. SASS详解之编译输出的样式

    SASS是一种CSS预处理语言,没有装环境的话是不能被解析的.但是有了koala编译工具之后,解析SASS不需要环境也毫无压力了.SASS的输出格式有四种:嵌套.扩大.紧凑和压缩.下面结合小例子为大家 ...

  7. jquery的$.each()

    each()方法能使DOM循环结构简洁,不容易出错.each()函数封装了十分强大的遍历功能,使用也很方便,它可以遍历一维数组.多维数组.DOM, JSON 等等在javaScript开发过程中使用$ ...

  8. .NET-DataTable或DataSet转JSON

    通过AJAX异步减少网络内容传输,而JSON则可以把传输内容缩减到纯数据:然后利用jQuery内置的AJAX功能直接获得JSON格式的数据:在客户端直接绑定到数据控件里面,从而达到最优. #regio ...

  9. 【转】word排版宏的使用

    原文: https://blog.csdn.net/bruce_shan/article/details/73302756 -------------------------------------- ...

  10. IIs 中运行asp程序出现“An error occurred on the server when processing the URL. Please contact the system administrator.”错误

    在个人的win08系统上使用IIs运行 asp程序结果出现了以下错误 An error occurred on the server when processing the URL. Please c ...