码迷,mamicode.com
首页 > Windows程序 > 详细

开始 ASP.NET Web API 2 之旅

时间:2015-11-08 14:01:33      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:

HTTP不仅仅是提供网页而已。它同时也是一个用于公开服务和数据的强大的API平台。HTTP简单、灵活,而且无处不在。你能想到的几乎所有的平台,都会有一个HTTP库,因此HTTP服务可以达到广泛的客户端,包括浏览器、移动设备,和传统的桌面应用程序。

ASP.NET Web API是一个用于构建基于.NET Framework 的 Web API 的框架。在本教程中,你将会使用ASP.NET Web API来创建返回一个产品列表的web API。

教程中使用的软件有:

Visual Studio 2013

Web API 2

创建 Web API 项目

在这个教程中,你将会使用ASP.NET Web API 来创建一个返回产品列表的web API。前端页面使用 jQuery 显示结果。

技术分享

打开Visual Studio,新建项目,选择ASP.NET Web 应用程序,如图:

技术分享

然后选择“Empty”模板,并在“核心引用”下面的选项中勾选“Web API”,

技术分享

你也可以用“Web API”项目模板来创建一个 Web API 项目。Web API 模板使用 ASP.NET MVC 来提供 API 帮助页。这个教程之所以选择空的模板是因为我想不通过 MVC 来演示 Web API。一般地说,使用 Web API 你不需要知道 ASP.NET MVC。

添加Model

Model是用来在你的程序中呈现数据的。ASP.NET Web API 能够自动把你的model序列化为 json、xml或者其他格式的数据,然后将数据序列化到HTTP响应消息的body中。当客户端读到相应的序列化格式后,它能够反序列化对象。大部分的客户端能够解析XML或者JSON。而且,客户端也可以通过HTTP请求头来指明它所需要的数据格式。

让我们开始创建一个简单的model用于呈现一个产品。在解决方案目录的Models中,添加一个“Product”类:

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }

添加一个Controller

在 Web API 中,controller用于处理http请求。我们添加一个controller用于返回产品列表和根据产品id返回单个产品。

注意:如果你已经用过ASP.NET MVC,你应该对controllers已经熟悉。Web API 的controller 和MVC的controller相类似,不过Web API的controller继承于ApiController,而MVC的controller继承于Controller。

在解决方案目录的Controllers中,添加一个控制器,选择基架“Web API 2 控制器 - 空”:

技术分享

ProductsController代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ProductsApp.Models;

namespace ProductsApp.Controllers
{
    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 IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
    }
}

在控制器中分别定义了两个方法:

GetAllProducts返回完整的产品列表,这个方法响应的URI为/api/products;

GetProduct方法通过产品id返回单个产品,这个方法响应的URI为/api/products/id

想要了解更多关于Web API的controller路由请求,请参考Routing in ASP.NET Web API

使用Javascript和jQuery请求Web API

在项目中添加一个html页面,代码如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <div>
        <h2>All Products</h2>
        <ul id="products" />
    </div>
    <div>
        <h2>Search by ID</h2>
        <input type="text" id="prodId" size="5" />
        <input type="button" value="Search" onclick="find();" />
        <p id="product" />
    </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
        var uri = api/products;

        $(document).ready(function () {
            // Send an AJAX request
            $.getJSON(uri)
                .done(function (data) {
                    // On success, ‘data‘ contains a list of products.
                    $.each(data, function (key, item) {
                        // Add a list item for the product.
                        $(<li>, { text: formatItem(item) }).appendTo($(#products));
                    });
                });
        });

        function formatItem(item) {
            return item.Name + : $ + item.Price;
        }

        function find() {
            var id = $(#prodId).val();
            $.getJSON(uri + / + id)
                .done(function (data) {
                    $(#product).text(formatItem(data));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $(#product).text(Error:  + err);
                });
        }
    </script>
</body>
</html>

获取产品列表

发送http get请求到“/api/products”

            $.getJSON(uri)
                .done(function (data) {
                    // On success, ‘data‘ contains a list of products.
                    $.each(data, function (key, item) {
                        // Add a list item for the product.
                        $(‘<li>‘, { text: formatItem(item) }).appendTo($(‘#products‘));
                    });
                });

通过id获取单个产品

发送http get请求到“/api/products/id”

            $.getJSON(uri + ‘/‘ + id)
                .done(function (data) {
                    $(‘#product‘).text(formatItem(data));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $(‘#product‘).text(‘Error: ‘ + err);
                });

运行项目:

技术分享

最后,你还可以F12调出浏览器的开发者工具查看页面的http请求和响应,也可以使用另一个工具Fiddler来查看http的请求/响应。

注:本文为译文,原文为:Getting Started with ASP.NET Web API 2 (C#)

开始 ASP.NET Web API 2 之旅

标签:

原文地址:http://www.cnblogs.com/laixiancai/p/4946129.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!