WCF实现RESTFul Web Service
共同学习了前面一些概念,终于开始正题了哈。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的更多相关文章
- WCF 、Web API 、 WCF REST 和 Web Service 的区别
WCF .Web API . WCF REST 和 Web Service 的区别 The .Net framework has a number of technologies that allow ...
- 转 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 ...
- 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 ...
- 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 ...
- 【转】基于CXF Java 搭建Web Service (Restful Web Service与基于SOAP的Web Service混合方案)
转载:http://www.cnblogs.com/windwithlife/archive/2013/03/03/2942157.html 一,选择一个合适的,Web开发环境: 我选择的是Eclip ...
- 【转】 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 ...
- Building a RESTful Web Service Using Spring Boot In Eclipse
一.构建restful web service 创建Maven的java web工程,maven的pom文件加入依赖包 创建包hello Greeting.java package hello; pu ...
- 使用Java创建RESTful Web Service
REST是REpresentational State Transfer的缩写(一般中文翻译为表述性状态转移).2000年Roy Fielding博士在他的博士论文“Architectural Sty ...
- (转)接口自动化测试 – Java+TestNG 测试 Restful Web Service
本文主要介绍如何用Java针对Restful web service 做接口自动化测试(数据驱动),相比UI自动化,接口自动化稳定性可靠性高,实施难易程度低,做自动化性价比高.所用到的工具或类库有 T ...
随机推荐
- [mark]如何删除地址栏的记录?
比如,我输入字母a ..因为经常访问.它首先会自动帮我补填 amazon.cn 第二行出现 ali213...第三行是 alipay... 这个很简单,没必要搞得很复杂很Geek.比如楼主的情况,首先 ...
- Matlab中下标,斜体,及希腊字母的使用方法
下面是Matlab官方列出来的Tex代码列表,包含了绝大部分的希腊字母和数学符号. Character Sequence Symbol Character Sequence Symbol Charac ...
- 用指令来构建IIS7
工作上要部署iis7+net4.0环境,发现30多台机子都没有用装有IIS7镜像来安装,都必须自己手动. 作为程序猿,真要一台台装的话,就真对不起自己的职业.于是想到用bat来执行任务,找到了安装II ...
- (转)行为树(Behavior Tree)
转自:http://www.cnblogs.com/konlil/archive/2011/04/23/2025954.html 如果要让游戏里的角色或者NPC能执行预设的AI逻辑,最简单的用IF.. ...
- Ext3.0中复杂表头样例
注意要点:不出现滚动栏时要设置height和forceFit : false 效果例如以下图: this.columns = [{ header : '月份', dataIndex : '月份', w ...
- Binwalk:后门(固件)分析利器
http://blog.csdn.net/testing_is_believing/article/details/14091179 Binwalk介绍 Binwalk是一个固件的分析工具,旨在协助研 ...
- java中形参个数可变的方法使用
public class Varargs { public static void main(String[] args) { test(3,"java","C++&qu ...
- 微信小程序 - 自定义components组件详解A篇
官网API:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/component.html 自定义 ...
- 查看正在执行的sql语句
;WITH t AS( SELECT [Spid] = session_Id, ecid, [Database] = DB_NAME(sp.dbid), [User] = nt_username, [ ...
- 深入理解javascript闭包【整理】
原文链接:http://www.cn-cuckoo.com/2007/08/01/understand-javascript-closures-72.html 英文原文:http://www.jibb ...