Web Api入门

http://blog.csdn.net/ojlovecd/article/details/8169822

 

初尝Web API

分类: ASP.NET MVC教程

目录(?)[+]

 

ASP.NET Web API 是.NET Framework上的一个框架,用来生成 web API。 本文将使用ASP.NET Web API来创建一个web API,返回一组商品。前端页面用jQuery来显示结果。

 

点此下载完整工程。

首先需要安装了ASP.NET MVC 4的 Visual Studio 。下面的用哪个都行:

  • Visual Studio Express 2012 for Web
  • ASP.NET MVC 4 。
  • ASP.NET MVC 4 。

如果用的是 Visual Studio 2010 或者 Visual Web Developer 2010 Express ,需要另外安装 ASP.NET MVC 4 。本文的截图都是用的 Visual Studio Express 2012 for Web。

创建 Web API 工程

在模板面板中,选择“已安装”,并展开 Visual C# 下面,选择 ASP.NET MVC 4 Web 应用程序。将项目命名为 "HelloWebAPI" 然后点击“确定”。

 

 ASP.NET MVC 4 项目”对话框中,选择“Web API”然后点“确定”。

 

添加模型

模型是指程序里的对象。 ASP.NET Web API 能够自动序列化模型为JSON,XML或者其它的格式,然后将序列化后的数据写入HTTP响应信息体里。只要客户端能读到序列化格式,它就能反序列化为对 象。大部分的客户端都能够解析XML或JSON。 而且,客户端通过设置HTTP请求信息里的Accept头就能够表明它想要什么样的格式。

如果解决方案资源管理器没显示的话,点击“视图”菜单并选择“解决方案资源管理器”。在解决方案资源管理器重,右击“Models”文件夹。在弹出菜单中,选择“添加“,”类“。

 

Product 类里加入下面的属性:

namespace HelloWebAPI.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
}

添加控制器

 

  • HomeController 是一个传统的 ASP.NET MVC 控制器。它只是负责处理站点的HTML页,跟Web API没有直接关系。
  • ValuesController 是一个示例 WebAPI 控制器。

注意  如 果你之前已经搞过 ASP.NET MVC,那你肯定已经对控制器很熟了。它在Web API里也是类似的,只不过在Web API里控制器不是从Controller类继承而是从ApiController类继承了。你会注意到,第一个主要的不同点是Web API上的操作并不返回视图,而是返回数据。

ValuesController, 选择”删除“直接把他删掉。

解决方案资源管理里,右击 Controllers 目录,选择”添加“,”控制器“:

 

 

 

”添加控制器“向导在Controllers目录下创建一个名为 ProductsController.cs 的控制器。

没有必要非得把控制器放到Controllers目录里。目录名并不重要,只是为了方便我们组织代码文件,这么起名比较简单。

namespace HelloWebAPI.Controllers {     using HelloWebAPI.Models;     using System;     using System.Collections.Generic;     using System.Linq;     using System.Net;     using System.Net.Http;     using System.Web.Http;     public class ProductsController : ApiController     {         Product[] products = new Product[]         {             new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },             new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },             new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }         };         public IEnumerable<Product> GetAllProducts()         {             return products;         }         public Product GetProductById(int id)         {             var product = products.FirstOrDefault((p) => p.Id == id);             if (product == null)             {                 throw new HttpResponseException(HttpStatusCode.NotFound);             }             return product;         }         public IEnumerable<Product> GetProductsByCategory(string category)         {             return products.Where(                 (p) => string.Equals(p.Category, category,                     StringComparison.OrdinalIgnoreCase));         }     } }

控制器定义了三个方法,要么返回单个商品,要么返回一组产品:

  • GetAllProducts 方法返回所有的产品,返回类型为  GetProductById 方法通过ID查询某个产品。
  • GetProductsByCategory 方法返回指定分类的所有产品。

控制器方法 URI GetAllProducts /api/products GetProductById /api/products/ GetProductsByCategory /api/products/?category= 客户端只要通过放松一个HTTP GET请求到URI就可以调用相应的方法。待会儿我们来看看这个映射是怎么做的。但首先我们先把它跑起来试试。

从浏览器调用 Web API 

在 Visual Studio 里,选择“调试”菜单,然后“启动调试”,或者按F5键。 ASP.NET Development Server 就会启动起来(译者注:在VS2012默认的应该是IIS Express), 在屏幕的右下角会出现一个通知图标,显示它正运行在哪个端口。默认情况下, Development Server 会选择一个随机的端口号。

http//localhost:xxxx/, xxxx 就是端口号。首页应该看起来如下图:

 

HomeController 类返回。想要调用 web API,就得用到前边儿列出来的URI之一。比如,要获取所有商品列表,那就浏览 xxxx" 替换为真实的端口号)

[{"Id":1,"Name":"Tomato soup","Category":"Groceries","Price":1.0},{"Id":2,"Name": "Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category": "Hardware","Price":16.99}]

自己浏览这俩 URI 试试:

  • http://localhost:xxxx/api/products?category=hardware

用JavaScript和jQuery调用 Web API 

在解决方案资源管理器重,展开Views目录,然后展开它下面的Home目录。可以看到一个名为Index.cshtml的文件。双击这个文件打开。

 

Razor 视图引擎 渲染HTML页。 但是此处我们不使用任何Razor特性,因为我要演示客户端如何使用纯HTML和Javascript访问服务。因此,删掉这个文件里的所有东西,用下面的代码替换之:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ASP.NET Web API</title>
    <link href="../../Content/Site.css" rel="stylesheet" />
    <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript">
        // TODO Add script
    </script>
</head>
<body id="body" >
    <div class="main-content">
        <div>
            <h1>All Products</h1>
            <ul id="products"/>
        </div>
        <div>
            <label for="prodId">ID:</label>
            <input type="text" id="prodId" size="5"/>
            <input type="button" value="Search" onclick="find();" />
            <p id="product" />
        </div>
    </div>
</body>
</html>

获取产品列表

<script type="text/javascript">     $(document).ready(function () {         // Send an AJAX request         $.getJSON("api/products/",         function (data) {             // On success, 'data' contains a list of products.             $.each(data, function (key, val) {                 // Format the text to display.                 var str = val.Name + ': $' + val.Price;                 // Add a list item for the product.                 $('<li/>', { text: str })                     .appendTo($('#products'));               });         });     }); </script>

getJSON 函数用来发送 AJAX 请求。 响应将是一个JSON对象数组。getJSON的第二个参数是一个回调函数,当请求成功完成时将调用。

通过ID获取产品

function find() {     var id = $('#prodId').val();     $.getJSON("api/products/" + id,         function (data) {             var str = data.Name + ': $' + data.Price;             $('#product').text(str);         })     .fail(         function (jqXHR, textStatus, err) {             $('#product').text('Error: ' + err);         }); }            

getJSON 函数来发送 AJAX 请求,但这次我们用ID来构造这个请求URI。这个请求的响应是一个JSON,表示单个产品对象。

<!DOCTYPE html> <html lang="en"> <head>     <title>ASP.NET Web API</title>     <link href="../../Content/Site.css" rel="stylesheet" />     <script src="../../Scripts/jquery-1.7.1.min.js"         type="text/javascript"></script>         <script type="text/javascript">             $(document).ready(function () {                 // Send an AJAX request                 $.getJSON("api/products/",                 function (data) {                     // On success, 'data' contains a list of products.                     $.each(data, function (key, val) {                         // Format the text to display.                         var str = val.Name + ': $' + val.Price;                         // Add a list item for the product.                         $('<li/>', { text: str })                         .appendTo($('#products'));                     });                 });             });             function find() {                 var id = $('#prodId').val();                 $.getJSON("api/products/" + id,                     function (data) {                         var str = data.Name + ': $' + data.Price;                         $('#product').text(str);                     })                 .fail(                     function (jqXHR, textStatus, err) {                         $('#product').text('Error: ' + err);                     });             }         </script> </head> <body id="body" >     <div class="main-content">         <div>             <h1>All Products</h1>             <ul id="products"/>         </div>         <div>             <label for="prodId">ID:</label>             <input type="text" id="prodId" size="5"/>             <input type="button" value="Search" onclick="find();" />             <p id="product" />         </div>     </div> </body> </html>

运行程序

理解路由

Routing in ASP.NET Web API.

/api/{id}

{controller} 和 {id} 是占位符。当框架看到匹配此模式的URI时,它会去找相应的方法来调用,匹配规则如下:

  • {controller} 与控制器名称匹配。
  • 可能的话,查询参数与参数名称匹配。

URI HTTP 方法 操作 /api/products GET GetAllProducts() /api/products/1 GET GetProductById(1) /api/products?category=hardware GET GetProductsByCategory("hardware")

{id} 段,所以框架去找没有参数的方法。ProductsController::GetAllProducts 方法满足所有这些要求。

{id} 部分。因此,框架调用 GetProduct,它有一个名为id的参数。还有,注意URI中值“5”作为id参数传入。框架会基于方法签名,自动将“5"转换为int类型。

URI HTTP 方法 操作 /api/products/ POST 405 Method Not Allowed /api/users/ GET 404 Not Found /api/products/abc GET 400 Bad Request

对于 /api/users 的请求失败,因为压根就没有名为 UsersController 的控制器。对 api/products/abc 的请求失败,因为id参数是int类型,而 URI 段的"abc" 无法转换为int。

使用 F12 查看 HTTP 请求和响应

 

 

Fiddler,一个web 调试代理。你可以用Fiddler来查看HTTP流量,还可以组合HTTP请求,这样你可以对请求中的HTTP标头进行完全控制。

下一步

 

  • Creating a Web API that Supports CRUD Operations
  • Contact Manager Web API Sample

 

  • Self-Host a Web API
  • Using Web API with ASP.NET Web Forms


原文地址:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

posted @ 2015-05-25 19:58  小蚕豆  阅读(212)  评论(0编辑  收藏  举报