使用ASP.NET web API创建REST服务(三)

本文档来源于:http://www.cnblogs.com/madyina/p/3390773.html

Creating a REST service using ASP.NET Web API

A service that is created based upon the architecture of REST is called as REST service. Although REST looks more inclined to web and HTTP its principles can be applied to other distributed communication systems also. One of the real implementation of REST architecture is the World Wide Web (WWW). REST based services are easy to create and can be consumed from a wide variety of devices.

REST (REpresentational State Transfer,表述性状态转移) 。REST 指的是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就是RESTful。

REST 定义了一组体系架构原则,您可以根据这些原则设计以系统资源为中心的 Web 服务,包括使用不同语言编写的客户端如何通过 HTTP 处理和传输资源状态。 如果考虑使用它的 Web 服务的数量,REST 近年来已经成为最主要的 Web 服务设计模式。 事实上,REST 对 Web 的影响非常大,由于其使用相当方便,已经普遍地取代了基于 SOAP 和 WSDL 的接口设计。

There are many APIs available in different languages to create and consume REST services. The ASP.NET MVC beta 4 comes with a new API called ASP.NET Web API to create and consume REST services. While creating REST services it is important to follow the rules and standards of the protocol (HTTP). Without knowing the principles of REST it is easy to create a service that looks RESTful but they are ultimately an RPC style service or a SOAP-REST hybrid service. In this article we are going to see how to create a simple REST service using the ASP.NET Web API.

ASP.NET MVC beta 4附带了API开发功能,同时可以调用ASP.NET Web API来创建和使用 REST 服务。创建其他服务时很重要的是要遵循标准的协议 (HTTP)。

在这篇文章我们来看看如何创建一个简单的ASP.NET Web API REST服务,并且调用它。

开发工具:Visual Studio 2013

创建步骤:

1. 模型化数据

  创建一个新的ASP.NET WEB项目,在如下图界面选择Empty模板并且勾上Web API选项。(这里我们不使用Asp.net Mvc4的方式去创建,我认为应该采用独立的方式去创建比较好)

然后再Model中创建一个类Person:

在这里您可能会在您认为合理的框架中使用Web API,所以我们只从原理上来描述它,不拘泥于具体的实现方式和设计模式。

接着在Model中创建一个接口IPersonRepository

然后,让我们去实现它。同样在Model中创建一个实现类PersonRepository

 在这个实现中不管您将采取任何数据来源XML,文件或者其他持久化存储,我们都可以返回一个实现了IEnumerable接口的列表,从而消除数据来源的差异性。

2. 使用Api Controllers 访问 API 服务

Unlike an ASP.NET/MVC Project, which generally uses Controllers derived from System.Web.MVC.Controller, a WebApi project will generally utilize controllers derived from System.Web.Http.WebApiController. Like the standard MVC Controller, The WebApi Controller accepts incoming HTTP requests and processes accordingly. However, the standard MVC Controller returns a View, while the WebApi controller returns data.

特别值得注意的是,WebApi controller会检查接受HTTP请求头部。然后将NET对象序列化为适当的返回数据类型(XML或JSON)。

在Controllers文件夹上右键选择添加—>控制器,然后如下图选择

命名为PersonController。

现在您可以方便的在这里添加任何GURD代码。我们一起来分析一个具体实现:

第一句代码可以说是实例化一个数据访问类,而我们要做的是根据ID返回要查询的Person对象,通过调用对应方法可以实现。注意观察这个方法是以Get方式开头,而这个方法包含一个id参数,这个方法会匹配/api/PersonController/id的请求,而请求中的参数id会自动转换为int类型

如果没有找到相应id的联系人,则会抛出一个自定义HttpResponseMessage的异常,这个异常是指向的404异常,表示请求资源不存在。实际项目中,我们是非常有必要返回一些和操作对应的异常信息的。

完整代码如:

As we have alluded to previously, a core tenet of MVC is to favor Convention over Configuration. In terms of our controller class, what this means is that the ASP.NET/MVC runtime establishes certain default behaviors which require no additional configuration, unless you want to change them. Initially, for me anyway, this was also a source of confusion, as the runtime appeared to perform sufficient "magic" that I didn't know what was happening.

当然其中一个非常重要的Web API规范就是HTTP谓词的映射,如GET、POST、PUT、DELETE。那么正如我们上面所述,我们的动作也遵循了这个规范。原因是在 ASP.NET Web API,一个 controller 是一个 class(类) 以处理 HTTP 请求(requests)。在 controller 里所有的公开方法(public methods)都称为 Action方法 或简称 Action。当 Web API Framework 接收到一个请求,它路由请求到一个 Action。

每个实体(entry)在路由表里都包含一个路由样板(route template)。Web API 的路由样板默认是 "api/{controller}/{id}",此样板里,"api" 是文字路径片段,{controller} 和 {id} 是定位参数。

当 Web API Framework 接收到一个 HTTP 请求,它会去尝试比对 URI 对路由表的路由样板列表, 如果没有符合的路由,Client 会收到一个 404 错误。例如,以下 URI 会符合默认路由:

· /api/Person

· /api/Person /1

路由表定义如:

1
2
3
4
5
6
7
8
9
config.Routes.MapHttpRoute(
 
 name: "Default",
 
 routeTemplate: "api/{controller}/{id}",
 
 defaults: new { id = RouteParameter.Optional }
 
 );

例如,一个 GET 请求,Web API 会查看那一个 action 是以 "Get..." 开头,比如 "GetContact" 或 "GetAllContacts"。同样规则适用在 GET, POST, PUT, DELETE 方法。你也能在 controller 里使用属性(attributes)去启用其他 HTTP 方法。

 以下是一些可能 HTTP 请求及其含义:

HTTP Method

URI路径

Action

参数

GET

/api/Person

GetAllPeople

GET

/api/Person /1

GetPersonByID

1

DELETE

/api/Person /1

DeletePerson

1

POST

/api/Person

PostPerson

newPerson

当然,我们可以根据自己的实际需要修改这个路由表,如:

1
2
3
4
5
config.Routes.MapHttpRoute(
 name: "Default",
 routeTemplate: "api/{controller}/{action}/{id}",
 defaults: new { id = RouteParameter.Optional }
 );

那么根据ID查询某个人就需要这样发送请求:

/api/person/ GetPersonByID/1

也可以访问到需要的资源。

3. 创建消费服务

       根据项目的需要,你可以在你的API的客户端添加一个Person类。webapi懂得如何序列化和反序列化。NET类中的JSON或XML,都是使用中最常见的两种数据交换格式。

          We can re-write our client examples to utilize a Person class if it suits our needs, and pass instances of Person to and from our API project indirectly through serialization. Our core client methods, re-written, look like this:

         我们以控制台程序为例,新建一个控制台项目,假设命名为:RestApiClient

         添加第一个类Person:         

        至于为什么要在这里还要添加一个Person类,我们可以想象WEB API机制,它是类似于Web Service的一种远程数据调用消息交换机制,服务器上使用的类本地是没有的,为了类型和序列化方便通常还要在消费端再次定义一次,加入您将消费放在服务端如以WCF的形式来进行,真正的客户端通过同步/异步请求来获取资源,那么另当别论。

然后新建一个类用来发送请求给WEB API,我们再次来分析这个类里面写些什么,列举一个方法:

     可以看出返回的是JArray格式。说明如下:

使用JSON前,需要引用Newtonsoft.Json的dll和using Newtonsoft.Json.Linq的命名空间。LINQ to JSON主要使用到JObject, JArray, JProperty和JValue这四个对象,JObject用来生成一个JSON对象,简单来说就是生成"{}",JArray用来生成一个JSON数组,也就是"[]",JProperty用来生成一个JSON数据,格式为key/value的值,而JValue则直接生成一个JSON值。下面我们就用LINQ to JSON返回上面分页格式的数据。

下面就是定义一个HttpClient去发送一个GET请求给指定WEB API,然后利用HttpResponseMessage接收返回的JSON数据。

完整代码如:

最不值钱的就是最终调用了,在Program类的Main方法中调用代码如下:

PS:

  1. 这里我偷了个懒,把他们写成一个部分类了,实际应该怎么写你懂得…
  2. 如果报每个方法最后一句出错,请加引用:"System.Net.Http.Formatting",可以在这里找到C:Program Files (x86)Microsoft ASP.NETASP.NET MVC 4AssembliesSystem.Net.Http.Formatting.dll真实的想法是实在不想加这个引用,原因请看下面。

    另外遗憾的一点是我们对服务的消费操作并没有使用到纯异步操作也没有使用配置,只因我们讲述的是最简单的原理,后面会逐渐构建起一个完整的框架。敬请期待!

源码下载:请点击

原文地址:https://www.cnblogs.com/wangoublog/p/5489670.html