ASP.NET Web API与Rest web api(一)
本文档内容大部分来源于:http://www.cnblogs.com/madyina/p/3381256.html
HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.
(HTTP不仅服务于网页。同时也是构建服务和数据API强大的平台。HTTP是简单的,灵活的,无处不在。几乎你所能想到的任何平台都有一个HTTP库,所以HTTP服务可以构建面向各种客户端的服务,包括浏览器,移动设备,与传统的桌面应用程序。)
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
But,Looks like the tide of the web API protocol war (if there ever was one) has shifted firmly in REST's favor while SOAP has been forced back. Web developers have cast their votes, they want RESTful APIs.
(现在看起来在Web API协议之争,潮流正稳步的转向REST,SOAP已经被减少,而很多Web开发者也都开始使用RESTful APIs,至少在目前看来,REST已经占据了API模式的统治地位。)
In this tutorial, you will use ASP.NET Web API to create a web API that returns a list of users. The front-end web page uses jQuery to display the results.
Requirements:
This tutorial uses Visual Studio 2013
Create a Web API Project
Like this:
Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.
1. In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET Web Application. Name the project "UsersApp" and click OK.
2. In the New ASP.NET Project dialog, select the Empty template. Under "Add folders and core references for", check Web API. Click OK.
3. Adding a Model
A model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message.
一个模型表示了一个对象,是应用程序数据的载体。ASP.NET Web API可以自动序列化你的模型成为XML,JSON,或一些其他的格式,然后输出数据到HTTP响应流。如果一个客户端可以读取序列化格式,那它也可以反序列化的对象。大多数客户端都能够解析XML或JSON。此外,客户端也希望通过设置接受HTTP请求报头格式。
Let's start by creating a simple model that represents a user.
If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class.
Name the class "User". Add the following properties to the User class.
1
2
3
4
5
6
7
8
9
|
namespace HelloWebApi.Models { public class User { public int ID { get ; set ; } public string user_key { get ; set ; } public string lower_user_name { get ; set ; } } } |
4. Adding a Controller
In Web API, a controller is an object that handles HTTP requests. We'll add a controller that can return either a list of users or a single user specified by ID.
In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.
In the Add Scaffold dialog, select Web API Controller - Empty. Click Add.
In the Add Controller dialog, name the controller "UserController". Click Add.
If this file is not open already, double-click the file to open it. Replace the code in this file with the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
namespace HelloWebApi.Controllers { public class UserController : ApiController { User[] users = new User[] { new User { ID = 1, lower_user_name = "石曼迪" , user_key = "mady" }, new User { ID = 2, lower_user_name = "狗王" , user_key = "taisanDog" }, new User { ID = 3, lower_user_name = "道长" , user_key = "kongque" } }; public IEnumerable<User> GetAllUsers() { return users; } public User GetUserById( int id) { var user = users.FirstOrDefault((p) => p.ID == id); if (user == null ) { throw new HttpResponseException(HttpStatusCode.NotFound); } return user; } } |
To keep the example simple, users are stored in a fixed array inside the controller class. Of course, in a real application, you would query a database or use some other external data source.
The controller defines two methods that return users:
- The GetAllUsers method returns the entire list of users as an IEnumerable<User> type.
- The GetUserById method looks up a single user by its ID.
That's it! You have a working web API. Each method on the controller corresponds to one or more URIs:
Controller Method |
URI |
GetAllUsers |
api/User/GetAllUsers |
GetUserById |
api/User/GetUserById/2 |
And then,change the Web API routes:
1
|
config.Routes.MapHttpRoute( name: "DefaultApi" , routeTemplate: "api/{controller}/{action}/{id}" , defaults: new { id = RouteParameter.Optional }); |
For the GetUserById method, the id in the URI is a placeholder. For example, to get the user with ID of 2, the URI is api/User/GetUserById/2
Press F5 to start debugging the application with URL:
http://localhost:1786/api/User/ GetAllUsers
The browser may return an errorlike this:
Use CMD to enter the directory:C:\Program Files\IIS Express
Execute a command:
1
|
appcmd set config /section:system.webServer/directoryBrowse /enabled: true |
If everything goes well you will see the results:
5. Adding a WebProject
In the Solution "HelloWebApi" right-click the project and select Add, then select Add New Item dialog, select the Web Project node under Visual C#, and then named WebApp.
Again, right-click the project "WebApp", In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page " Test.html".
Replace everything in this file with the following:
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
|
<! DOCTYPE html> < head > < title >My Web API App</ title > </ head > < body > < div > < h2 >All Users</ h2 > < ul id="Users" /> </ div > < div > < h2 >Search by ID</ h2 > < input type="text" id="UID" size="5" /> < input type="button" value="Search" onclick="find();" /> < p id="User" /> </ div > < script > var uri = 'http://localhost:1786/api/User'; $(document).ready(function () { // 发送一个 AJAX 请求给指定网址 $.getJSON(uri + '/GetAllUsers') .done(function (data) { // 当城管时结果应该是包含数据的JSON. $.each(data, function (key, item) { // 为Users标签添加列表 $('< li >', { text: formatItem(item) }).appendTo($('#Users')); }); }); }); function formatItem(item) { return item.user_key + ': ' + item.lower_user_name; } function find() { var id = $('#UID').val(); $.getJSON(uri + '/GetUserById/' + id) .done(function (data) { $('#User').text(formatItem(data)); }) .fail(function (jqXHR, textStatus, err) { $('#User').text('Error: ' + err); }); } </ script > </ body > </ html > |
Getting a List of Users
To get a list of users, send an HTTP GET request to "/api/user/GetAllUsers".
The jQuery getJSON function sends an AJAX request. For response contains array of JSON objects. The done function specifies a callback that is called if the request succeeds. In the callback, we update the DOM with the user information.
1
|
[{"ID":1,"user_key":"mady","lower_user_name":"石曼迪"},{"ID":2,"user_key":"taisanDog","lower_user_name":"狗王"},{"ID":3,"user_key":"kongque","lower_user_name":"道长"}] |
Getting a User By ID
To get a user by ID, send an HTTP GET request to "/api/user/ GetUserById/id", where id is the user ID.
We still call getJSON
to send the AJAX request, but this time we put the ID in the request URI. The response from this request is a JSON representation of a single user.
1
|
{"ID":2,"user_key":"taisanDog","lower_user_name":"狗王"} |
6. Running the Application
Press F5 to start debugging the application. The web page should look like the following:
To get a user by ID, enter the ID and click Search:
If you enter an invalid ID, the server returns an HTTP error:
Using F12 to View the HTTP Request and Response
When you are working with an HTTP service, it can be very useful to see the HTTP request and request messages. You can do this by using the F12 developer tools in Internet Explorer 9. From Internet Explorer 9, press F12 to open the tools. Click the Network tab and press Start Capturing. Now go back to the web page and press F5 to reload the web page. Internet Explorer will capture the HTTP traffic between the browser and the web server. The summary view shows all the network traffic for a page:
If you click the Response body tab, you can see how the user list was serialized to JSON. Other browsers have similar functionality. Another useful tool is Fiddler, a web debugging proxy. You can use Fiddler to view your HTTP traffic, and also to compose HTTP requests, which gives you full control over the HTTP headers in the request.
The source code download Please Click Here
ASP.NET Web API与Rest web api(一)的更多相关文章
- Request Entity Too Large for Self Hosted ASP.Net Web API在Selfhost的api后台怎么解决Request Entity Too Large问题
Request Entity Too Large for Self Hosted ASP.Net Web API在Selfhost的api后台怎么解决Request Entity Too Large问 ...
- ASP.NET Core 1.0开发Web API程序
.NET Core版本:1.0.0-rc2Visual Studio版本:Microsoft Visual Studio Community 2015 Update 2开发及运行平台:Windows ...
- ASP.NET Web API与Rest web api(一)
HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that exp ...
- 002.Create a web API with ASP.NET Core MVC and Visual Studio for Windows -- 【在windows上用vs与asp.net core mvc 创建一个 web api 程序】
Create a web API with ASP.NET Core MVC and Visual Studio for Windows 在windows上用vs与asp.net core mvc 创 ...
- ASP.NET Core MVC中构建Web API
在ASP.NET CORE MVC中,Web API是其中一个功能子集,可以直接使用MVC的特性及路由等功能. 在成功构建 ASP.NET CORE MVC项目之后,选中解决方案,先填加一个API的文 ...
- ASP.NET MVC Web API 学习笔记---Web API概述及程序示例
1. Web API简单说明 近来很多大型的平台都公开了Web API.比如百度地图 Web API,做过地图相关的人都熟悉.公开服务这种方式可以使它易于与各种各样的设备和客户端平台集成功能,以及通过 ...
- ASP.NET MVC 4 (十二) Web API
Web API属于ASP.NET核心平台的一部分,它利用MVC框架的底层功能方便我们快速的开发部署WEB服务.我们可以在常规MVC应用通过添加API控制器来创建web api服务,普通MVC应用程序控 ...
- ASP.NET Web API 框架研究 Web Host模式路由及将请求转出到消息处理管道
Web Host 模式下的路由本质上还是通过ASP.NET 路由系统来进行路由的,只是通过继承和组合的方式对ASP.NET路由系统的内部的类进行了一些封装,产生自己专用一套类结构,功能逻辑基本都是一样 ...
- 【ASP.NET Web API2】初识Web API
Web Api 是什么? MSDN:ASP.NET Web API 是一种框架,用于轻松构建可以访问多种客户端(包括浏览器和移动设备)的 HTTP 服务 百度百科:Web API是网络应用程序接口. ...
随机推荐
- 一模 (4) day1
第一题: 题目大意:给出N个人之间转账的手续X%,求出A转给B至少要多少钱才能使B得到100元.结果保留8位小数:N<=2000 解题过程: 1.很容易看出这题的图论模型,每条边的权值就是(1- ...
- C# 子窗体点击按钮产生的新子窗体放在父窗体里
情景展示: 父窗体Form1,左边是按钮,右边是panel(放置子窗体) 父窗体点击按钮,在panel显示第一个子窗体AA, AA有个按钮,点击按钮,是第二个子窗体ZZ, 怎样将AA的子窗体ZZ也显示 ...
- 使用rosed编辑ROS文件
1.1使用rosed. rosed是rosbash套件的一部分.它可以使你通过package的名字直接编辑一个package中的文件而不用输入package的整个路径. 用法: $ rosed [pa ...
- 理解ROS rqt_console和 roslaunch
1.使用rqt_console和roslaunch 这篇教程将介绍使用rqt_console和rqt_logger_level来调试以及使用roslaunch一次启动许多nodes.如果你使用ROS ...
- limit 百万级数据分页优化方法
mysql教程 这个数据库教程绝对是适合dba级的高手去玩的,一般做一点1万 篇新闻的小型系统怎么写都可以,用xx框架可以实现快速开发.可是数据量到了10万,百万至千万,他的性能还能那么高吗? 一点小 ...
- [开发笔记]-使用bat命令来快速安装和卸载Service服务
一般我们在编写完Service服务程序后,都是通过cmd命令提示窗口来安装或卸载服务,但频繁的在cmd窗口中去“拼”文件的路径着实让人“不能忍”.所以,我们需要一钟“更快捷”的方式来进行安装或者卸载操 ...
- Noip2014 提高组 day1 T1· 生活大爆炸版石头剪刀布
生活大爆炸版 石头剪刀布 描述 石头剪刀布是常见的猜拳游戏:石头胜剪刀,剪刀胜布,布胜石头.如果两个人出拳一 样,则不分胜负.在<生活大爆炸>第二季第 8 集中出现了一种石头剪刀布的升级版 ...
- namenode 无法启动之每次开机需要重新格式化-tmp
最近遇到了一个问题,执行start-all.sh的时候发现JPS一下namenode没有启动 每次开机都得重新格式化一下namenode才可以 其实问题就出在tmp文件,默 ...
- JVM-class文件完全解析-方法表集合
方法表集合 前面的魔数,次版本号,主板本号,常量池入口,常量池,访问标志,类索引,父类索引,接口索引集合,字段表集合,那么再接下来就是方法表了. 方法表的构造如同字段表一样,依次包括了访问标志(a ...
- goldengate 12c 针对oracle 12c配置的主要变化
由于oracle 12c已经是多租户架构,在使用OGG同步的时候,需要考虑下面一些情况 一个 CDB包含多个PDB,源端部署的一个extract可访问所有pdb redo,理论上不需要每个pdb单独配 ...