开始一个简单的ASP.NET Web API 2 ,C#

创建一个Web API 项目

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

选择ASP.NET Web Application,新建名ProductsApp

在弹出框里选择空的模板,并把Web API勾选上,点击OK。

注意

添加一个Model

从上下文菜单中,选择Add然后选择类。

C#

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

添加一个控制器Controller

选择Add然后选择控制器。

In the Add Scaffold dialog, select Web API Controller - Empty. Click Add.

ProductsController.cs 在Controllers文件夹内

C#

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

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);
        }
    }
}

复制例子代码到controller类中。

定义了2个方法返回产品

  • GetAllProducts 方法返回类型IEnumerable<Product>
  • GetProduct 方法查找单个产品通过ID

控制器上的每个方法对应于一个或多个uri:

Controller MethodURI
GetAllProducts/api/products
GetProduct/api/products/id

例如 GetProduct 方法, id 在 URI 是一个占位符,假设id是5: api/products/5.

调用Web API 通过 Javascript and jQuery

在解决方案资源管理器中,右键单击项目并选择添加,然后选择新的项目。

html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Product App</title>
</head>
<body>

  <div>
    <h2>All Products</h2>
    <ul  />
  </div>
  <div>
    <h2>Search by ID</h2>
    <input type="text"  size="5" />
    <input type="button" value="Search" onclick="find();" />
    <p  />
  </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>

得到一个产品列表

html

$(document).ready(function () {
    // Send an AJAX request
    $.getJSON(apiUrl)
        .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得到产品

JavaScript

function find() {
    var id = $('#prodId').val();
    $.getJSON(apiUrl + '/' + id)
        .done(function (data) {
            $('#product').text(formatItem(data));
        })
        .fail(function (jqXHR, textStatus, err) {
            $('#product').text('Error: ' + err);
        });
}

运行应用

按下F5 开始 调试应用,页面如下

1

输入ID

如果你输入一个无效的ID,将返回错误

使用F12 来查看HTTP Request and Response

摘要视图显示一个页面的所有网络流量:

例如,如果您单击请求头选项卡,您可以看到客户端请求“application / json”Accept标头。

您可以使用Fiddler查看HTTP流量,并构成HTTP请求,这让你完全控制请求中的HTTP头。