REST服务

概述

Representational State Transfer(REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。

因此REST是设计风格而不是标准,REST通常基于使用HTTP,URI,和JSON,XML以及HTML这些现有的广泛流行的协议和标准。
  • 资源是由URI来指定,rest中的资源需要使用名词来命名。
  • 对资源的操作包括获取、创建、修改和删除资源,这些操作正好对应HTTP协议提供的GET、POST、PUT和DELETE方法。
  • 通过操作资源的表形来操作资源。
  • 资源的表现形式则是XML,JSON或者两者都有。
REST的要求
  • 显示的使用HTTP方法访问资源
  • 连接协议具有无状态性
  • 能够利用Cache机制增进性能
  • 公开目录结构式的URL
  • 在需要时可以传输Javascript (可选)
REST的优点
  • 可以利用缓存Cache来提高响应速度
  • 通讯本身的无状态性可以让不同的服务器的处理一系列请求中的不同请求,提高服务器的扩展性
  • 浏览器即可作为客户端,简化软件需求
  • 相对于其他叠加在HTTP协议之上的机制,REST的软件依赖性更小
  • 不需要额外的资源发现机制
  • 在软件技术演进中的长期的兼容性更好

在WCF中构建REST

一、按一下结构创建项目,其中WCF.REST.Services项目选用WCF REST Service Template 40(CS)模板

Contracts引用System.ServiceModel和System.ServiceModel.Web

Services引用Contracts

二、在Contracts项目中创建接口个传输类:传输类会在调用的客户端等地方使用,建议使用全小写,以免调用时产生疏忽。


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

using System;

namespace WCF.REST.Contracts

{

    /// <summary>

    /// 该类用于传输

    /// </summary>

    public class item

    {

        public int id { get; set; }

        public string name { get; set; }

        public decimal money { get; set; }

        public DateTime birthday { get; set; }

        public int number { get; set; }

    }

}

三、在Contracts项目中创建协议接口:在这里定义接口,方便维护,将接口和实现类进行分离。


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

using System.Collections.Generic;

using System.ServiceModel;

using System.ServiceModel.Web;

namespace WCF.REST.Contracts

{

    /// <summary>

    /// 服务协议

    /// </summary>

    [DataContractFormat]

    [ServiceContract]

    public interface IItem

    {

        [WebGet(UriTemplate = "")]

        List<item> GetCollection();

        [WebInvoke(UriTemplate = "", Method = "POST")]

        item Create(item instance);

        [WebGet(UriTemplate = "{id}")]

        item Get(string id);

        [WebInvoke(UriTemplate = "{id}", Method = "PUT", BodyStyle = WebMessageBodyStyle.WrappedRequest)]

        item Update(string id, item instance);

        [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]

        void Delete(string id);

    }

}

四、在Services中创建逻辑类,用于存储列表:真实项目时这个类可以单独放在业务逻辑层中。


1

2

3

4

5

6

7

8

9

10

11

12

13

using System.Collections.Generic;

using WCF.REST.Contracts;

namespace WCF.REST.Services

{

    /// <summary>

    /// 服务逻辑

    /// </summary>

    public static class ItemsBL

    {

        public static List<item> list = new List<item>();

    }

}

五、在Services中创建服务类:这是服务的具体实现。


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

using System.Collections.Generic;

using System.Linq;

using System.ServiceModel.Activation;

using WCF.REST.Contracts;

namespace WCF.REST.Services

{

    /// <summary>

    /// 服务实现

    /// </summary>

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    public class Items : IItem

    {

        public List<item> GetCollection()

        {

            return ItemsBL.list;

        }

        public item Create(item instance)

        {

            lock (ItemsBL.list)

            {

                if (ItemsBL.list.Count > 0)

                    instance.id = ItemsBL.list.Max(p => p.id) + 1;

                else

                    instance.id = 1;

            }

            ItemsBL.list.Add(instance);

            return instance;

        }

        public item Get(string id)

        {

            return ItemsBL.list.FirstOrDefault(p => p.id == int.Parse(id));

        }

        public item Update(string id, item instance)

        {

            int iid = int.Parse(id);

            item Result = null;

            lock (ItemsBL.list)

            {

                if (ItemsBL.list.Count(p => p.id == iid) > 0)

                {

                    ItemsBL.list.Remove(ItemsBL.list.FirstOrDefault(p => p.id == iid));

                    ItemsBL.list.Add(instance);

                    Result = instance;

                }

            }

            return Result;

        }

        public void Delete(string id)

        {

            int iid = int.Parse(id);

            lock (ItemsBL.list)

            {

                if (ItemsBL.list.Count(p => p.id == iid) > 0)

                {

                    ItemsBL.list.Remove(ItemsBL.list.FirstOrDefault(p => p.id == iid));

                }

            }

        }

    }

}

六、修改Global文件如下:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

using System;

using System.ServiceModel.Activation;

using System.Web;

using System.Web.Routing;

namespace WCF.REST.Services

{

    public class Global : HttpApplication

    {

        void Application_Start(object sender, EventArgs e)

        {

            RegisterRoutes();

        }

        private void RegisterRoutes()

        {

            RouteTable.Routes.Add(new ServiceRoute("Items", new WebServiceHostFactory(), typeof(Items)));

        }

    }

}

七、运行服务在地址栏后添加 /items/help 后看到如下界面

ok至此服务部分完成。

时间: 2024-08-08 16:08:09

REST服务的相关文章

mysqld服务启动失败, Failed to restart mysqld.service: Unit not found.

-bash-4.2# service mysqld restart Redirecting to /bin/systemctl restart mysqld.serviceFailed to restart mysqld.service: Unit not found. 并不存在 mysqld 的服务, -bash-4.2# -bash-4.2# chkconfig -list -list: unknown option -bash-4.2# chkconfig --list Note: Thi

SQL Server 2008的MSSQLSERVER 请求失败或服务未及时响应

我的是SQL server 2008R2, 以前可以正常的启动SQL server(SQLEXPRESS).SQL server(MSSQLSERVER),有几天没有打开了,就在昨天 开机之后就无法启动MSSQLSERVER了,提示的信息如下图: 快速解决办法如下: 第一步:打开事件查看器,查看windows日志,点击应用程序,查看windows错误日志 http://product.pconline.com.cn/itbk/software/win8/1211/3060037.html 第二步

dubbo之服务降级

向注册中心写入动态配置覆盖规则:(通过由监控中心或治理中心的页面完成) RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); Registry registry = registryFactory.getRegistry(URL.valueOf("zookeeper://10.20.153.10:2181"))

Windows Server 2012配置L2TP服务环境

在上一篇文章<Windows Server 2012配置VPN服务环境>中讲解了在Windows Server2012环境中的基础VPN搭建,但是只能支持PPTP的VPN连接.这篇文章进一步完善了VPN基于L2TP的连接讲解. 在百度上也没有找到一个Windows2012 很全的L2TP服务搭建的方案,所以自己编辑了一个给有需要的朋友们参考. 准备环境:Windows Server 2012R2 数据中心版64位,基础的VPN服务环境已经搭建完成. 功能需求:完善VPN服务器来支持L2TP类型

Windows 无法启动xx服务 错误1053:服务没有及时响应启动或控制请求

症状:win7系统的很多系统关键服务,启动不了,双击该服务也弹不了操作框,系统服务是设置为自动 的,但是就是启动不了,在本地服务窗口中只能启动该服务,但是双击会弹不了窗口,你点启动后会出现错误提示1053,本地用户组,里面可以看到用户和组但 是双击话也没反应,照成后果,网站打不开,远程连接连不上,但是服务器实际上是开着的,其实具体原因就是因为系统关键服务未正常开启,实验结果表明是权限 不够,导致系统服务一律停止,为什么会这样呢?估计是服务器中毒,被木马程序影响照成的,照成了Network Ser

自定义及发布一个webservice服务

自定义及发布一个webservice服务    - 声明 某个业务服务为webservice服务       通过@webservice 注解来声明    - 发布webservice服务       Endpoint.publish()发布 (默认对public修饰的方法进行发布)    - 通过wsimport生成本地代理来访问自己发布的webservice       wsimport 1.发布自定义webservice phone.java package ws.myWebService

C# 远程服务器 安装、卸载 Windows 服务,读取远程注册表,关闭杀掉远程进程

这里安装windows服务我们用sc命令,这里需要远程服务器IP,服务名称.显示名称.描述以及执行文件,安装后需要验证服务是否安装成功,验证方法可以直接调用ServiceController来查询服务,也可以通过远程注册表来查找服务的执行文件:那么卸载文件我们也就用SC命令了,卸载后需要检测是否卸载成功,修改显示名称和描述也用sc命令.至于停止和启动Windows服务我们可以用sc命令也可以用ServiceController的API,当停止失败的时候我们会强制杀掉远程进程,在卸载windows

Windows Server下把BAT批处理注册成服务在后台运行且注销后能正常运行

批处理有如下特点: 1.登录到当前窗口运行时,如果关闭控制台会连同启动的程序一起关闭. 2.如果是以start /b的形式启动,那么同样也是在控制台关闭后者注销当前窗口也会一起关闭. 3.如果以vbs的形式启动,注销当前用户也会一起关闭. 有如下方式解决: 1.使用[任务计划]去启动批处理,里面有很多个触发点,可以选择[计算机启动时]触发也能达到开机启动的效果,而不用登录桌面. 2.有错误启动Windows Service方式,用[sc]命令注册服务,然后以cmd.exe的形式去启动(C:\Wi

Spring Cloud ZooKeeper集成Feign的坑2,服务调用了一次后第二次调用就变成了500,错误:Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is com.n

错误如下: 2017-09-19 15:05:24.659 INFO 9986 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]56528192: startup date [Tue Sep 19 15:05:24 CST 2017]; root of context hierarchy 2017-09-19 15:05:24.858 INFO 9986 --

mongodb 安装、windows服务、创建用户

http://www.cnblogs.com/best/p/6212807.html 打开MongoDB的安装目录如“C:\Program Files\MongoDB\Server\3.4\bin”,并在此目录下新建一个mongo.config文件,文件内容如下: ##数据库目录## dbpath=C:\data\db ##日志输出文件## logpath=C:\data\log\db.log 使用cmd进入命令行 使用cd切换目录到安装目录下,如:cd  C:\Program Files\Mo