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

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请求

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfRestFulService { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. [ServiceContract(Name="user")]
public interface IService1
{
[OperationContract] [WebInvoke(UriTemplate = "get/{value}", Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] string GetData(string value); [OperationContract] [WebInvoke(UriTemplate = "add", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] string addPeople(People p); [OperationContract] [WebInvoke(UriTemplate = "GetList/{value}", Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] List<People> GetList(string value); } }

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

4、  Service1.svc实现契约

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
namespace WcfRestFulService
{ // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together. [AspNetCompatibilityRequirements(
RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string GetData(string value)
{
return string.Format("You entered: {0}", value);
} public string addPeople(People p)
{
if (p == null)
{
return "People is Null";
}
return p.Name;
} public List<People> GetList(string value) { return new List<People> { new People(){Id=1,Name="eric"}}; }
}
}

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

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;
using System.ServiceModel.Activation;
namespace WcfRestFulService
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RegistrRoutes();
}
private void RegistrRoutes()
{
//说明:ServiceRoute需要引用 System.ServiceModel.Activation.dll
RouteTable.Routes.Add(new ServiceRoute("user", new WebServiceHostFactory(), typeof(Service1)));
}
}
}

6、  Web.config配置文件

<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="defaultResultBehavior">
<!-- 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="false"/>
<dataContractSerializer maxItemsInObjectGraph="6553500"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="defaultRestEndpointBehavior">
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" />
<dataContractSerializer maxItemsInObjectGraph="6553500"/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="WcfRestFulService.Service1" behaviorConfiguration="defaultResultBehavior">
<endpoint binding="webHttpBinding" contract="WcfRestFulService.IService1" behaviorConfiguration="defaultRestEndpointBehavior"></endpoint>
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</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/1 和 http://localhost:9315/Default.aspx

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

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

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

调用服务string GetData(string value)

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

调用服务:string addPeople(People p)

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

调用服务GetList(string value)

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

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

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

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

 
 
 
标签: WCFRESTFul

WCFRESTFul服务搭建及实现增删改查的更多相关文章

  1. [收藏转贴]WCFRESTFul服务搭建及实现增删改查

    RESTful Wcf是一种基于Http协议的服务架构风格,  RESTful 的服务通常是架构层面上的考虑. 因为它天生就具有很好的跨平台跨语言的集成能力,几乎所有的语言和网络平台都支持 HTTP ...

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

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

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

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

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

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

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

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

  6. Python Web实战:Python+Django+MySQL实现基于Web版的增删改查

    前言 本篇使用Python Web框架Django连接和操作MySQL数据库学生信息管理系统(SMS),主要包含对学生信息增删改查功能,旨在快速入门Python Web,少走弯路.效果演示在项目实战最 ...

  7. AngularJS中使用$http对MongoLab数据表进行增删改查

    本篇体验使用AngularJS中的$http对MongoLab数据表进行增删改查. 主页面: <button ng-click="loadCourse()">Load ...

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

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

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

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

随机推荐

  1. 【iOS开发-48】九宫格布局案例:自己主动布局、字典转模型运用、id和instancetype差别、xib反复视图运用及与nib关系

    本次九宫格案例: (1)导入app.plist和各种图片素材,方便兴许开发.实际开发中,也是如此. (2)把plist中数组导入进来. --由于本案例中app.plist终于是一个数组,数组里面是字典 ...

  2. .net mvc mssql easyui treegrid

    效果图 数据图   可以看到 这里是根据 MenuNo 来 分级别的,支持 无限极,第一级是 01 ,第二级就是 01XX ,第三级 就是 01XXOO.类似 id.pid ,Ztree 里面 也是这 ...

  3. 提高mysql千万级数据SQL的查询优化30条总结

    1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引. 2.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索 ...

  4. AngularJS学习笔记(一)——一些基本知识

    (一)Hello Angular index.html <!DOCTYPE html> <html ng-app> <head> <title>Test ...

  5. The operator == is undefined for the argument type(s) int, null

    package cn.edu.shu.web.test; public class TestInteger { public static void main(String[] args) { /** ...

  6. SQL点滴13—收集SQLServer线程等待信息

    原文:SQL点滴13-收集SQLServer线程等待信息 要知道线程等待时间是制约SQL Server效率的重要原因,这一个随笔中将学习怎样收集SQL Server中的线程等待时间,类型等信息,这些信 ...

  7. 【转】NuGet的安装与使用

    学习了一段时间的MVC,今天想自己尝试初步搭建一个MVC框架,结果新建MVC4.0(MVC3.0同样)项目时,弹出一个错误提示框,如下图.上网一搜,说是要安装一个第三方组件NuGet.刚接触MVC,更 ...

  8. MySql处理数据库和表

    show databases; mysql> show databases; mysql> create database db_test; Query OK, 1 row affecte ...

  9. 缓存,spring

    applicationcontext.xml xmlns:cache="http://www.springframework.org/schema/cache" xsi:schem ...

  10. 在Idea中调试ant应用

    Ant调试 Ant调试 ant 是一种非常方便的打包,部署的工具,通过ant,可以一键构建整个项目,虽然MVN也支持这种功能,但是MVN混杂了package管理的功能,并且不是很自由,学习成本比较高. ...