Fork me on GitHub
WCF 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)模板

imageimage

 

Contracts引用System.ServiceModelSystem.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 后看到如下界面

image

ok至此服务部分完成。

分类: 技术
标签: WCF

技术

摘要: Representational State Transfer(REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。 因此REST是设计风格而不是标准,REST通常基于使用HTTP,URI,和JSON,XML以及HTML这些现有的广泛流行的协议和标准。阅读全文

posted @ 2012-04-16 10:34 ☆磊☆ 阅读(731) | 评论 (4) 编辑 |

摘要: uploadify 控件的按钮不支持多国语言,这里介绍如何修改后使其支持多国语言。 1.jquery.uploadify.v2.1.4.js文件 70行 原代码:if (settings.buttonText) data.buttonText = escape(settings.buttonText); 新代码:if (settings.buttonText) data.buttonText = ...阅读全文

posted @ 2011-11-09 14:42 ☆磊☆ 阅读(460) | 评论 (0) 编辑 |

摘要: Stream.Write 与 StreamWriter.Write 是我们在向流中写数据时,最常用的方法。下面就详细讲解这两个方法。一、测试方法是否结果相同首先看下面两段代码左侧是StreamWriter.Write 右侧是Stream.Write:Stream ms = new MemoryStream();string str = "这是测试字符串";StreamWriter sw = new StreamWriter(ms, Encoding.UTF8);sw.Write(str);sw.Flush();Stream ms = new MemoryStream();s阅读全文

posted @ 2011-11-02 09:10 ☆磊☆ 阅读(1553) | 评论 (8) 编辑 |

摘要: 前段时间需要这个功能,但是找了很多都不能完美的实现,不是只能锁定表头,就是浏览器兼容问题什么的,在此就自己做了一个锁定表头和列的js方法,依赖于JQuery。因为方法很简单,就未封装成插件的形式,仅仅以代码方式发布。这里把自己做的方式写出来,以资纪念。支持IE6+,FF3.6+,Opera9+,Chrome9+一、实现方式这里的准备使用4个table实现,具体如下图:上图红色部分为要取出来的部分,蓝色部分为拼接后可以看到的部分。最终结果如下图实现后效果:姓名班级成绩主科文科理科总分语文数学英语政治历史地理物理化学生物 姓名 班级 语文 ...阅读全文

posted @ 2011-06-30 08:37 ☆磊☆ 阅读(5102) | 评论 (32) 编辑 |

摘要: 在项目中经常会用到一些样式什么的,如果使用了jQuery UI那么很多的图标,样式什么的,就可以尽量使用jQuery UI里面已经定义好了的,在此就对jQuery UI中的css做写了下注释,提供自己...阅读全文

posted @ 2011-03-14 13:26 ☆磊☆ 阅读(3641) | 评论 (2) 编辑 |

摘要: Silverlight 为常见变换变换包括旋转 (RotateTransform)、缩放 (ScaleTransform)、扭曲 (SkewTransform) 和平移 (TranslateTransform)。 还有一个MatrixTransform 类可以创建 RotateTransform、ScaleTransform、SkewTransform 和 TranslateTransform ...阅读全文

posted @ 2010-09-27 13:31 ☆磊☆ 阅读(1623) | 评论 (2) 编辑 |

摘要: 多线程部分 多线程在4.0中被简化了很多,仅仅只需要用到System.Threading.Tasks.::.Task类,下面就来详细介绍下Task类的使用。 一、简单使用 开启一个线程,执行循环方法,返回结果。开始线程为Start(),等待线程结束为Wait()。 Code /// <summary> /// Task简单使用 /// </summary> priv...阅读全文

posted @ 2010-09-18 12:38 ☆磊☆ 阅读(1713) | 评论 (2) 编辑 |

摘要: 并行计算部分 沿用微软的写法,System.Threading.Tasks.::.Parallel类,提供对并行循环和区域的支持。 我们会用到的方法有For,ForEach,Invoke。一、简单使用 首先我们初始化一个List用于循环,这里我们循环10次。(后面的代码都会按这个标准进行循环)Code Program.Data = new List<int>(); for (int ...阅读全文

posted @ 2010-09-16 16:21 ☆磊☆ 阅读(2347) | 评论 (8) 编辑 |

摘要: 一、情景如果你的项目中有返回多结果集的存储过程。如果你的项目要和老项目中的ADO.Net共用事务。如果你要动态的创建数据库的表。但是你还是希望使用Entity Framework。那么继续往下看吧。二、ADO.NET Entity Framework Extensions(下载地址)1、引用EFExtensions.dll文件。2、添加 using Microsoft.Data.Extensions; 的声明。三、EFExtensions执行T-SQL语句 public void ExecuteSQL(string sql) { using (DBEntities db = new D...阅读全文

posted @ 2010-08-16 15:32 ☆磊☆ 阅读(2114) | 评论 (6) 编辑 |

摘要: 本汉化文件部分翻译取自 《1.3.2.min-vsdoc》 文件及 《jQuery 1.4.1 中文参考》。如有错误请联系。在需要有智能提示的页面使用如下方式引用:<% if (false) { %> <script type="text/javascript" src="JScript/jquery-1.4.1.min-vsdoc"></script> <...阅读全文

posted @ 2010-03-10 15:34 ☆磊☆ 阅读(4293) | 评论 (15) 编辑 |

posted on 2012-04-16 21:30  HackerVirus  阅读(270)  评论(0编辑  收藏  举报