第一個 ASP.NET Web API應用程序


      HTTP 不只是用於生成 web 頁面。它也是功能強大的平台,用於構建公開服務和數據的 Api。HTTP 是簡單、靈活並且無處不在。所以 HTTP 客戶端服務范圍非常廣泛,包括瀏覽器、 移動設備和傳統的桌面應用程序。ASP.NET Web API 是用於生成 web Api 在.NET 框架上的框架。在本教程中,您將使用 ASP.NET Web API 創建的 web API 返回的產品列表。前端 web 頁使用 jQuery 來顯示結果。

 

啟動 Visual Studio 時,從開始頁中選擇新項目或者,從文件菜單中,選擇新建,然后項目.

模板窗格中選擇已安裝的模板和展開Visual C#節點。Visual C#中,選擇Web在項目模板的列表中,選擇ASP.NET MVC 4 Web 應用程序"HelloWebAPI"項目命名並單擊確定.

 

新的 ASP.NET MVC 4 項目對話框中,選擇Web API並單擊確定.

 

 

添加Model

一個Model對象,表示您的應用程序中的數據模型ASP.NET Web API 可以自動序列化到 JSON、 XML 或一些其他格式,然后將序列化的數據寫入 HTTP 響應消息的正文。只要客戶端可以讀取序列化格式,它可以反序列化對象。大多數客戶端可以解析 XML 或 JSON。讓我們首先創建一個簡單的Model,此示例中用來代表一種產品。如果解決方案資源管理器中不可見,請單擊視圖菜單,然后選擇解決方案資源管理器在解決方案資源管理器中,右鍵單擊模型文件夾。從上下文菜單中,選擇添加,然后選擇.

 

命名類"Product"。下一步,將下列屬性添加到 Product類。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

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

}

 

     控制器是一個對象,用於處理 HTTP 請求。如果您使用過 ASP.NET MVC ,然后您已熟悉控制器。那么同樣應用在Web API 中,但是Web API 中的控制器從ApiController類而不是控制器類派生的。還有一個主要區別是 Web API 控制器上的行動返回不是視圖,而是返回數據。

  

添加一個新的控制器,如下所示:

解決方案資源管理器中,右鍵單擊控制器文件夾。選擇添加,然后選擇控制器.

 

 

添加控制器向導中,命名為"ProductsController"的控制器。模板下拉列表中選擇空 API 控制器然后單擊添加.

添加控制器向導將創建一個名為控制器文件夾中的 ProductsController.cs 文件。

添加下面的實現:

using HellowWebApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace HellowWebApi.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 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方法 返回IEnumerable <Product>類型的產品的整個列表。
  • GetProductById方法 根據產品Id查找一個單一的產品。
  • GetProductsByCategory方法 返回與指定類別的所有產品。

 

 每個控制器上的方法映射到一個 URI:

 

控制器的方法 URI
GetAllProducts /api/products
GetProductById /api/products/id
GetProductsByCategory /api/products/?category=category

客戶端可以調用該方法,通過發送一個 HTTP GET 請求的 uri。稍后,我們來看看這種映射如何完成的。首先,讓我們試試看。

 

使用瀏覽器調用 Web API

 打開瀏覽器 輸入http://localhost:xxxx/api/products/(替換"xxxx"為實際的端口數目。)

具體的結果取決於您所使用的 web 瀏覽器。Ie 瀏覽器將提示您打開或保存一個名為Product的"文件".

"文件",實際上就是 HTTP 響應的正文。單擊打開。在打開方式對話框中選擇記事本。單擊確定,出現提示時,單擊打開。該文件應包含數組的產品 JSON 表示形式:

 在Mozilla Firefox,將顯示為 XML 格式在瀏覽器中。

差異的理由是 Ie 和火狐瀏覽器發送標頭接受不同,因此 web API 在響應中發送不同的內容類型。

可以嘗試請求瀏覽到這些 Uri:
•http://localhost:xxxx/api/products/1
•http://localhost:xxxx/api/products?category=hardware

第一次應返回的條目 id 等於 1。第二個應回到"硬件"所有類別的產品平等的列表,(在本例中,單個項目)。

 

使用Javascript 和 jQuery 調用 Web API

     在前一節中,我們調用直接從瀏覽器請求的 web API。但大部分的 web Api由客戶端應用程序以編程方式使用。所以讓我們寫一個簡單的 javascript 客戶端。在解決方案資源管理器中,展開視圖文件夾中。雙擊以打開一個名為 Index.cshtml 的文件。

Index.cshtml使用razor 視圖引擎呈現,本例中我們不使用任何的razor 語法,我們使用純html和javascript的方式。

將文本修改為以下內容:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>ASP.NET Web API</title> 
    <link href="http://www.cnblogs.com/Content/Site.css" rel="stylesheet" /> 
    <script src="http://www.cnblogs.com/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>

 

獲取產品的列表
若要獲取產品的列表,"api/products"發送一個 HTTP GET 請求。您可以使用 jQuery,如下所示:

<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

若要獲取產品按 ID,將發送到 HTTP GET 請求"/id",其中id是產品 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);  
        }); 
}            

下面的代碼顯示完整的 Index.cshtml 文件:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>ASP.NET Web API</title> 
    <link href="http://www.cnblogs.com/Content/Site.css" rel="stylesheet" /> 
    <script src="http://www.cnblogs.com/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>

 

運行應用程序

 按 f5 鍵以啟動調試應用程序。在 web 頁應如下所示:

 

詳情請參考: http://www.asp.net/web-api/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM