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 ...
随机推荐
- Visual Studio的工程结构解析
废话不多说,首先查看下一个简单的sln文件结构 Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio ...
- matlab 图像常用函数
Canny function [ canny ] = canny( rgb ) temp=rgb2gray(rgb); canny=edge(temp,'canny'); end 灰度 temp=rg ...
- EF Power Tools使用介绍
EF Power Tools可以从数据库反向生成实体及映射文件.一般在使用EF,有Database First,Code First以及Model First.常用的是Database ...
- java.lang.Integer can not be cast to java.lang.Long
hibernate 查询出来的结果 id 是int类型,xml文件配置的是int, 在jython 中调用hibernate 进行查询.字段的类型是java.lang.Long, 直接将id 传进去, ...
- Webview 支持文件上传
默认情况下情况下,在一个带有input tpye=file标签的Html页面,使用Android的WebView是不能够支持上传文件的(在iOS和微信上完全正常工作).而这个,也是在我们的前端工程师告 ...
- C#类的访问修饰符
默认情况下,类声明为内部的,即只有当前工程中的代码才能访问它.可以用internal访问修饰符关键字显式指定,但这不是必须的,类在定义时默认为此类型的类.但是C# 方法默认访问级别: private. ...
- Javascript里面的时间处理:将时间戳或时间对象转成字符串格式
问题背景:想把一个时间直接转成字符串格式 通过查api发现有个toLocaleString(),根据本地时间格式,把 Date 对象转换为字符串 new Date().toLocaleString() ...
- vb.net中将DataGridView与数据源绑定
在< .net中将DataGridView内的数据导出为Excel表格>中说了如何导出数据到Excel,今天这篇文章将讲述如何绑定数据源,在控件中显示我们需要的信息. 在敲机房收费系统的时 ...
- linux 的命令 -exec 的使用
linux中的 exec命令,-exec 后面跟的是linux的 command 命令,exec命令以分号结束‘:’, 该分号前面要放 反斜杠转义 . find . -name jquery.js - ...
- angularjs库及ionic库下载地址
angularjs库下载地址: 下载地址:https://code.angularjs.org/ 引用地址:http://www.bootcdn.cn/angular.js/ ionic库下载地址: ...