RESTful Wcf是一种基于Http协议的服务架构风格,  RESTful 的服务通常是架构层面上的考虑。 因为它天生就具有很好的跨平台跨语言的集成能力,几乎所有的语言和网络平台都支持 HTTP 请求,无需去实现复杂的客户端代理,无需使用复杂的数据通讯方式既可以将我们的服务暴露给任何需要的人,无论他使用 VB、Ruby、JavaScript,甚至是 HTML FORM,或者直接在浏览器地址栏输入

WCF 中通过 WebGetAttribute、WebInvokeAttribute (GET/PUT/POST/DELETE)、UriTemplate 定义 REST 的服务的调用方式, 通过 WebMessageFormat (Xml/Json) 定义消息传递的格式。

RESTful的几点好处(引用博文):

1、简单的数据通讯方式,基于HTTP协议。避免了使用复杂的数据通讯方式。

2、避免了复杂的客户端代理。

3、直接通过URI资源定向即可把服务暴露给调用者。

下面就通过一个简单的列子一步一步实现WCFRESTFul

1、  新建如下项目

  

2、  项目文件介绍

(1)     IService1.cs 定义服务契约,在接口方法中定义RestFul请求规则

(2)     Service1.svc 实现IService1.cs定义的服务契约。

(3)     People.cs 数据契约,定义的实体对象

(4)     Global.asax 全局资源文件中定义注册路由

(5)     Web.config 配置WCF服务。

3、  IService1.cs接口定义三个方法,包含GET和POST请求

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.Serialization;
  5. using System.ServiceModel;
  6. using System.ServiceModel.Web;
  7. using System.Text;
  8. namespace WcfRestFulService
  9.  
  10. {
  11.  
  12. // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
  13.  
  14. [ServiceContract(Name="user")]
  15. public interface IService1
  16. {
  17. [OperationContract]
  18.  
  19. [WebInvoke(UriTemplate = "get/{value}", Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  20.  
  21. string GetData(string value);
  22.  
  23. [OperationContract]
  24.  
  25. [WebInvoke(UriTemplate = "add", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  26.  
  27. string addPeople(People p);
  28.  
  29. [OperationContract]
  30.  
  31. [WebInvoke(UriTemplate = "GetList/{value}", Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  32.  
  33. List<People> GetList(string value);
  34.  
  35. }
  36.  
  37. }

注意:通过WebInvoke属性的Method值说明该请求的类型,UriTemplate值说明url路由。接口中[ServiceContract(Name="user")]的定义,我们的URL路径中将会用到user

4、  Service1.svc实现契约

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.Serialization;
  5. using System.ServiceModel;
  6. using System.ServiceModel.Web;
  7. using System.Text;
  8. using System.ServiceModel.Activation;
  9. namespace WcfRestFulService
  10. {
  11.  
  12. // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
  13.  
  14. [AspNetCompatibilityRequirements(
  15. RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  16. public class Service1 : IService1
  17. {
  18. public string GetData(string value)
  19. {
  20. return string.Format("You entered: {0}", value);
  21. }
  22.  
  23. public string addPeople(People p)
  24. {
  25. if (p == null)
  26. {
  27. return "People is Null";
  28. }
  29. return p.Name;
  30. }
  31.  
  32. public List<People> GetList(string value)
  33.  
  34. {
  35.  
  36. return new List<People> { new People(){Id=,Name="eric"}};
  37.  
  38. }
  39. }
  40. }

注意:[AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]的定义跟我们在webconfig中的一个配置相关,我们 在下文中详细介绍。

5、  Global全局资源文件,注册服务的路由:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.SessionState;
  7. using System.Web.Routing;
  8. using System.ServiceModel.Activation;
  9. namespace WcfRestFulService
  10. {
  11. public class Global : System.Web.HttpApplication
  12. {
  13. protected void Application_Start(object sender, EventArgs e)
  14. {
  15. RegistrRoutes();
  16. }
  17. private void RegistrRoutes()
  18. {
  19. //说明:ServiceRoute需要引用 System.ServiceModel.Activation.dll
  20. RouteTable.Routes.Add(new ServiceRoute("user", new WebServiceHostFactory(), typeof(Service1)));
  21. }
  22. }
  23. }

6、  Web.config配置文件

  1. <?xml version="1.0"?>
  2. <configuration>
  3. <system.web>
  4. <compilation debug="true" targetFramework="4.0" />
  5. </system.web>
  6. <system.serviceModel>
  7. <behaviors>
  8. <serviceBehaviors>
  9. <behavior name="defaultResultBehavior">
  10. <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
  11. <serviceMetadata httpGetEnabled="true"/>
  12. <!-- 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 -->
  13. <serviceDebug includeExceptionDetailInFaults="false"/>
  14. <dataContractSerializer maxItemsInObjectGraph="6553500"/>
  15. </behavior>
  16. </serviceBehaviors>
  17. <endpointBehaviors>
  18. <behavior name="defaultRestEndpointBehavior">
  19. <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" />
  20. <dataContractSerializer maxItemsInObjectGraph="6553500"/>
  21. </behavior>
  22. </endpointBehaviors>
  23. </behaviors>
  24. <services>
  25. <service name="WcfRestFulService.Service1" behaviorConfiguration="defaultResultBehavior">
  26. <endpoint binding="webHttpBinding" contract="WcfRestFulService.IService1" behaviorConfiguration="defaultRestEndpointBehavior"></endpoint>
  27. </service>
  28. </services>
  29. <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
  30. </system.serviceModel>
  31. <system.webServer>
  32. <modules runAllManagedModulesForAllRequests="true"/>
  33. </system.webServer>
  34. </configuration>

说明:在配置文件中我们看<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />节点,如果使aspNetCompatibilityEnabled="true"必须在Service1.svc声明 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)],其中RequirementsMode的值也可以为 AspNetCompatibilityRequirementsMode. Required

至此我们的WCFRESFul搭建成功,运行服务看效果。

1、  http://localhost:9315/Service1.svc(传统的页面,是不是很熟悉)

2、http://localhost:9315/user/help(RESTFul的风格,是不是眼前一亮

3、  通过RESTFul风格调用服务

(1)、http://localhost:9315/user/get/1调用服务string GetData(string value),参数值为1

(2)、http://localhost:9315/user/add 调用string addPeople(People p)服务

下面我们开始创建一个简答的ajax调用列子测试一下WC FRESTFul服务

注意:如果你是用VS自带的IIS调试,WCF RESTFul生成的URL与调用WCF服务的URL端口号要保持一致,要不然用ajax调用浏览器会认为跨域。 比如:http://localhost:9315/user/get/1http://localhost:9315/Default.aspx

我是采用win7系统的IIS 7调试的。

服务地址配置为:http://localhost/wfcrestful/user/help

调用服务的Web页面的地址为:http://localhost/restfulTest/WebForm1.aspx

调用服务string GetData(string value)

  1. $.get("http://localhost/wfcrestful/user/get/1", function (json) { alert(json) });

调用服务:string addPeople(People p)

  1. $.ajax({
  2. "url": "http://localhost/wfcrestful/user/add",
  3. "type": "POST",
  4. "contentType": "application/json",
  5. "dataType": "json",
  6. "data": '{\"Id\":1,\"Name\":\"我是输入的内容\"}',
  7. "success": function (returnValue) {
  8. alert(returnValue);
  9. }
  10.  
  11. });

调用服务GetList(string value)

  1. $.get("http://localhost/wfcrestful/user/GetList/22", function (json) {
  2. alert(json[0].Name);
  3. })

至此整个DEMO已经完成,请点击下载源码。

PS:WCF RESTFul已经是过时的技术了,有兴趣的童鞋们可以研究一下 MVC WebApi

文中有些的不对的地方欢迎大家指正。

[收藏转贴]WCFRESTFul服务搭建及实现增删改查的更多相关文章

  1. WCFRESTFul服务搭建及实现增删改查

    WCFRESTFul服务搭建及实现增删改查 RESTful Wcf是一种基于Http协议的服务架构风格,  RESTful 的服务通常是架构层面上的考虑. 因为它天生就具有很好的跨平台跨语言的集成能力 ...

  2. 基于SSM搭建网站实现增删改查

    网站源码地址:https://github.com/MyCreazy/BasicOperateWebSite.git 使用maven搭建网站的时候,记得选用war包格式,有时候maven包没有引用进来 ...

  3. 使用 Spring Boot 搭建一套增删改查(无多余代码)

    前言 这是我学习 Spring Boot 的第三篇文章,终于可以见到效果了.错过的同学可以看看之前的文章 我们为什么要学习 Spring Boot Spring Boot 入门详细分析 在入门的基础上 ...

  4. Arcgis api for js实现服务端地图的增删改查

    < !DOCTYPE html > <html xmlns = "http://www.w3.org/1999/xhtml" > <head > ...

  5. 使用IDEA搭建SpringBoot进行增删改查

    功能环境:java1.8以上  .IntellJIDEA  First: 创建项目,请根据项目图一步一步完成建立. 二.配置数据库 三.创建实体对象建表或对应存在表,根据需要加入相应注解 四.创建应用 ...

  6. 基于SpringBoot开发一个Restful服务,实现增删改查功能

    前言 在去年的时候,在各种渠道中略微的了解了SpringBoot,在开发web项目的时候是如何的方便.快捷.但是当时并没有认真的去学习下,毕竟感觉自己在Struts和SpringMVC都用得不太熟练. ...

  7. IDEA搭建SSM实现登录、注册,数据增删改查功能

     本博文的源代码:百度云盘/java/java实例/SSM实例/SSM实现登录注册,增删改查/IDEA搭建SSM实现登录,注册,增删改查功能.zip 搭建空的Maven项目 使用Intellij id ...

  8. 在ASP.NET MVC4中实现同页面增删改查,无弹出框01,Repository的搭建

    通常,在同一个页面上实现增删改查,会通过弹出框实现异步的添加和修改,这很好.但有些时候,是不希望在页面上弹出框的,我们可能会想到Knockoutjs,它能以MVVM模式实现同一个页面上的增删改查,再辅 ...

  9. node-express项目的搭建并通过mongoose操作MongoDB实现增删改查分页排序(四)

    最近写了一个用node来操作MongoDB完成增.删.改.查.排序.分页功能的示例,并且已经放在了服务器上地址:http://39.105.32.180:3333. Mongoose是在node.js ...

随机推荐

  1. 安卓数据存储(3):SQLite数据库存储

    SQLite简介 Google为Andriod的较大的数据处理提供了SQLite,他在数据存储.管理.维护等各方面都相当出色,功能也非常的强大.SQLite具备下列特点: 1.轻量级:使用 SQLit ...

  2. Android的Manifest配置文件介绍

    一.关于AndroidManifest.xml       AndroidManifest.xml 是每个android程序中必须的文件.它位于整个项目的根目录,描述了package中暴露的组件(ac ...

  3. 主机访问 虚拟机web注意事项

    在这里, 我通过NAT的方式, 通过主机访问虚拟机. 需要做的是, 将主机中访问的端口, 映射为虚拟机的'编辑->虚拟网络编辑器->vmnet8', 如下图 在弹出的'映射传入端口'界面中 ...

  4. Ext.Net学习笔记04:Ext.Net布局

    ExtJS中的布局功能很强大,常用的布局有border.accordion.fit.hbox.vbox等,Ext.Net除了将这些布局进行封装以外,更是对border进行了一些非常实用的改进,让我们来 ...

  5. JDBC实现往MySQL插入百万级数据

    想往某个表中插入几百万条数据做下测试, 原先的想法,直接写个循环10W次随便插入点数据试试吧,好吧,我真的很天真.... DROP PROCEDURE IF EXISTS proc_initData; ...

  6. LA 3708 Graveyard(推理 参考系 中位数)

    Graveyard Programming contests became so popular in the year 2397 that the governor of New Earck -- ...

  7. Java基础巩固----泛型

    注:参考书籍:Java语言程序设计.本篇文章为读书笔记,供大家参考学习使用 1.使用泛型的主要优点是能够在编译时而不是在运行时检查出错误,提高了代码的安全性和可读性,同时也提高了代码的复用性. 1.1 ...

  8. ubuntu基本使用

    sudo nautilus xxx指定目录去打开 这个命令就是以root权限打开一个窗口,来管理文件

  9. js监听

    IE浏览器监听: function attachEvent(string eventFlag, function eventFunc) eventFlag: 事件名称,但要加上on,如onclick. ...

  10. 这 30 类 CSS 选择器,你必须理解!

    CSS 选择器是一种模式,用于选择需要添加样式的元素.平时使用最多也是最简单的就是 #id..class 和标签选择器,在 CSS 中还有很多更加强大更加灵活的选择方式,尤其是在 CSS3 中,增加了 ...