共同学习了前面一些概念,终于开始正题了哈。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. 理解JavaScript中的事件流

    原文地址:http://my.oschina.net/sevenhdu/blog/332014 目录[-] 事件冒泡 事件捕获 DOM事件流 当浏览器发展到第四代时(IE4和Netscape Comm ...

  2. git和SVN的差别

    1)GIT是分布式的.SVN不是: 这 是GIT和其它非分布式的版本号控制系统,比如SVN.CVS等.最核心的差别.优点是跟其它同事不会有太多的冲突.自己写的代码放在自己电脑上,一段时间后再提交.合并 ...

  3. List of Chromium Command Line Switches(命令行开关集)——官方指定命令行更新网址

    转自:http://peter.sh/experiments/chromium-command-line-switches/ There are lots of command lines which ...

  4. 如何获取Android唯一标识(唯一序列号)

    有很多场景和需求你需要用到手机设备的唯一标识符. 在Android中,有以下几种方法获取这样的ID. 1. The IMEI: 仅仅只对Android手机有效: 1 2 TelephonyManage ...

  5. DICOM中的入门概念

    DICOM标准是医学影像界技术人员逃不掉的标准.本系列专题是JATI对DICOM标准的阐述,力图使PACS管理员和软件工程师都能理解. DICOM标准的提出者DICOM标准委员会是ISO组织的合作者. ...

  6. WEB漏洞挖掘技术总结

    漏洞挖掘技术一直是网络攻击者最感兴趣的问题,漏洞挖掘的范围也在随着技术的提升而有所变化.在前期针对缓冲区溢出.格式化字符串.堆溢出.lib库溢出等技术都是针对ELF文件(Linux可执行文件)或者PE ...

  7. django 基础知识回顾

    内容回顾: 1. ajax参数 url: type: data: 1.value不能是字典 {k1:'v1',k2:[1,2,3,],k3; JSON.string} 2.$('').serilize ...

  8. org.springframework.beans.NotWritablePropertyException

    刚碰到了这个异常,最后发现是bean配置xml文件中的属性名多了一个空格,这就是xml配置spring的弊端啊. 感谢百度,迅速定位了问题. https://yq.aliyun.com/article ...

  9. RS报表设计采用Total汇总过滤出错

    错误信息: DMR 子查询计划失败,并产生意外错误.: java.lang.NullPointerException 如图 原因是在RS过滤器中添加了: total([门诊人次] for [明细科室] ...

  10. 基于java语言的给cube添加custom view来实现权限控制

    今天是农历2014年的最后一个工作日了,在这里提前祝大家新年快乐.羊年大吉!当然本人今天也拿出来点儿真东西,做为献给大家的新年礼物,依次共勉. 下文主要讲述的是使用Java代码来完成对cube基于部门 ...