一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - ASP.NET教程 - 通過HttpClient 調(diào)用ASP.NET Web API示例

通過HttpClient 調(diào)用ASP.NET Web API示例

2020-04-24 14:33MeJoy ASP.NET教程

本篇文章主要介紹了通過HttpClient 調(diào)用ASP.NET Web API示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

在前面兩篇文章中我們介紹了ASP.NET Web API的基本知識和原理,并且通過簡單的實例了解了它的基本(CRUD)操作。我們是通過JQueryAjaxWeb API進行數(shù)據(jù)操作。這一篇我們來介紹一下使用HttpClient的方式來對Web API進行數(shù)據(jù)操作。

這里我們還是繼續(xù)使用對Product的操作實例來演示一下它的基本應(yīng)用。

 

創(chuàng)建ASP.NET Web API應(yīng)用程序 

VS中選擇創(chuàng)建一個ASP.NET Web Application應(yīng)用程序,在向?qū)У南乱粋€窗口中選擇Web API模板。

通過HttpClient 調(diào)用ASP.NET Web API示例

 

創(chuàng)建Model

這里我們在Models文件夾下創(chuàng)建一個簡單的Product model類,用來傳遞數(shù)據(jù)。

Models文件夾上點擊右鍵,選擇Add -> Class

 
    public class Product
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public decimal Price { get; set; }
        public int Count { get; set; }
        public string Description { get; set; }
    }
 

 

創(chuàng)建Cotroller

接著在Controllers文件夾下創(chuàng)建一個API Controller, 命名為"ProductsController"。

Controllers文件夾上點擊右鍵,選擇Add -> Controller ,在彈出向?qū)е羞x擇Web API 2 Controller - Empty

通過HttpClient 調(diào)用ASP.NET Web API示例

在向?qū)乱徊街休斎?strong>API Controller name為"ProductsController"。

通過HttpClient 調(diào)用ASP.NET Web API示例

因為我們需要通過HttpClient的方式來調(diào)用Web API,所以這里我們還需要創(chuàng)建一個MVC Controller

同樣在Controllers文件夾上點擊右鍵,選擇Add -> Controller ,在彈出向?qū)е羞x擇MVC 5 Controller - Empty

通過HttpClient 調(diào)用ASP.NET Web API示例

在向?qū)乱徊街休斎?strong>MVC 5 Controller name為"ProductController"。

通過HttpClient 調(diào)用ASP.NET Web API示例

 

創(chuàng)建Web API方法(CRUD)

這里我們依然使用模擬的數(shù)據(jù)創(chuàng)建簡單的CRUD Web API方法。前面的章節(jié)有詳細講解到,這里就不細說了。直接上代碼。

 
    public class ProductsController : ApiController
    {
        // Mock product list
        public static List<Product> productList = initProductMockDataList();

        private static List<Product> initProductMockDataList()
        {
            return new List<Product>()
            {
                new Product {ProductID=1,ProductName="Product A",Price=1000000,Count=5,Description="Description A"},
                new Product {ProductID=2,ProductName="Product B",Price=200000,Count=2,Description="Description B"},
                new Product {ProductID=3,ProductName="Product C",Price=500000,Count=8,Description="Description C"},
                new Product {ProductID=4,ProductName="Product D",Price=80000,Count=10,Description="Description D"},
                new Product {ProductID=5,ProductName="Product E",Price=300000,Count=3,Description="Description E"}
            };
        }

        public IEnumerable<Product> Get()
        {
            return productList;
        }

        public Product Get(int id)
        {
            return productList.Where(p => p.ProductID == id).FirstOrDefault();
        }

        public void Post([FromBody]Product product)
        {
            var lastProduct = productList.OrderByDescending(p => p.ProductID).FirstOrDefault();
            int newProductID = lastProduct.ProductID + 1;
            product.ProductID = newProductID;

            productList.Add(product);
        }

        public void Put([FromBody]Product product)
        {
            var currentProduct = productList.Where(p => p.ProductID == product.ProductID).FirstOrDefault();
            if (currentProduct != null)
            {
                foreach (var item in productList)
                {
                    if (item.ProductID.Equals(currentProduct.ProductID))
                    {
                        item.ProductName = product.ProductName;
                        item.Price = product.Price;
                        item.Count = product.Count;
                        item.Description = product.Description;
                    }
                }
            }
        }

        public void Delete(int id)
        {
            Product product = productList.Where(p => p.ProductID == id).FirstOrDefault();

            productList.Remove(product);
        }
    }
 

 

通過JQuery和Ajax調(diào)用MVC Controller,在MVC Controller中通過HttpClient調(diào)用Web API

Web API中的(CRUD)方法創(chuàng)建完成,接下來我們就分別來看看對各個方法的數(shù)據(jù)操作。

1.獲取Product列表

打開我們創(chuàng)建好的MVC 5 Controller文件ProductController。使用HttpClient的方式來調(diào)用我們Web API中的列表方法。

首先需要引入System.Net.Http

using System.Net.Http;

接下來為我們的Web API地址定義一個公共靜態(tài)變量。

 
        public static readonly Uri _baseAddress = new Uri("http://localhost:21853/"); 

        //
        // GET: /Product/
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetProductList()
        {
            List<Product> productList = null;
            Uri address = new Uri(_baseAddress, "/api/products");

            using (var httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync(address).Result;

                if (response.IsSuccessStatusCode)
                    productList = response.Content.ReadAsAsync<List<Product>>().Result;
            }

            return Json(productList, JsonRequestBehavior.AllowGet);
        }
 

這里我們需要通過點擊按鈕,通過Ajax調(diào)用來獲取Product列表數(shù)據(jù),所以這里我們使用JsonResult返回數(shù)據(jù)。

接下來,我們就來創(chuàng)建View

文件夾Views->Product下創(chuàng)建一個View,名為"Index"。打開Index View,修改頁面代碼如下:

 
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
</head>
<body>
    <div style="background-color: #008000; padding: 10px; margin: 5px; width: 45%;">
        <div style="font-weight: bold; margin-bottom: 5px;">Get Product List</div>
        <div style="padding-bottom:5px;"><input id="btnGetProductList" name="btnGetProductList" type="button" value="Get Product List" /></div>
        <div id="products"></div>
    </div>
   </body>
</html>
 

接著,我們要做的是,當點擊Get Product List按鈕是加載Product List代碼實現(xiàn)如下:

 
        $('#btnGetProductList').click(function () {
            $.ajax({
                url: '/Product/GetProductList',
                type: 'GET',
                dataType: 'json'
            }).success(function (result) {
                DisplayProductList(result);
            }).error(function (data) {
                alert(data);
            });
        });

        // Display product list
        function DisplayProductList(result) {
            var productTable = $("<table cellpadding='3' cellspacing='3'></table>");
            var productTableTitle = $("<tr><th>Product ID</th><th>Product Name</th><th>Price</th><th>Count</th><th>Description</th></tr>");
            productTableTitle.appendTo(productTable);

            for (var i = 0; i < result.length; i++) {
                var productTableContent = $("<tr><td>"
                    + result[i].ProductID + "</td><td>"
                    + result[i].ProductName + "</td><td>"
                    + result[i].Price + "</td><td>"
                    + result[i].Count + "</td><td>"
                    + result[i].Description + "</td></tr>");

                productTableContent.appendTo(productTable);
            }

            $('#products').html(productTable);
        }
 

好了,運行代碼。

點擊Get Product List按鈕之前如下:

通過HttpClient 調(diào)用ASP.NET Web API示例

點擊Get Product List按鈕之后如下:

通過HttpClient 調(diào)用ASP.NET Web API示例

Product數(shù)據(jù)列表加載成功。

 

2.獲取單條Product數(shù)據(jù)

這里我們的做法是在搜索框里輸入Product ID,然后點擊Get Product按鈕,查找出這條Product信息。

首先,我們先完成在ProductController中使用HttpClient調(diào)用Web API中獲取單條Product數(shù)據(jù)的方法。

 
        public JsonResult GetSingleProduct(int id)
        {
            Uri address = new Uri(_baseAddress, "/api/products/" + id);
            Product product = null;

            using (var httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync(address).Result;

                if (response.IsSuccessStatusCode)
                    product = response.Content.ReadAsAsync<Product>().Result;
            }

            return Json(product, JsonRequestBehavior.AllowGet);
        }
 

接著,來到Index View頁面中添加一個搜索Product IDtextbox以及一個Get Product的按鈕。

 
    <div style="background-color: #9ACD32; padding: 10px; margin: 5px; width: 45%; ">
        <div style="font-weight:bold;margin-bottom:5px;">Get Single Product</div>
        <div>Product ID:&nbsp;<input id="txtSearchProductID" name="txtSearchProductID" type="text" />&nbsp;<input id="btnGetProduct" name="btnGetProduct" type="button" value="Get Prdouct" /></div>
        <div id="product"></div>
    </div>
 

為按鈕Get Product按鈕添加Ajax方法

 
       $('#btnGetProduct').click(function () {
            if ($('#txtSearchProductID').val().trim() != "") {
                $.ajax({
                    url: '/Product/GetSingleProduct?id=' + $('#txtSearchProductID').val(),
                    type: 'GET',
                    dataType: 'json'
                }).success(function (result) {
                    if (result != null) {
                        $('#product').html("Product ID: " + result.ProductID + "<br/>" + "Product Name: " + result.ProductName + "<br/>" + "Count: " + result.Count + "<br/>" + "Price: " + result.Price + " <br/>" + "Description: " + result.Description);
                    } else {
                        $('#product').html('');
                    }
                }).error(function (data) {
                    alert(data);
                });
            }
        });
 

運行程序,加載Product列表。
點擊Get Product按鈕前:

通過HttpClient 調(diào)用ASP.NET Web API示例

這里我們查找Product ID為1的數(shù)據(jù)

通過HttpClient 調(diào)用ASP.NET Web API示例

我們看到Product ID1的數(shù)據(jù)成功獲取。

 

3.新增一條Product

這里我們創(chuàng)建4個textbox,用來輸入Product Name,Count,Price,Description的信息以及一個Create Product按鈕。

首先,我們先完成在ProductController中使用HttpClient調(diào)用Web API中新增一條Product數(shù)據(jù)的方法。

 
        public JsonResult CreateProduct(Product product)
        {
            bool createSuccess = true;
            Uri address = new Uri(_baseAddress, "/api/products");

            using(var httpClient=new HttpClient())
            {
                var response = httpClient.PostAsJsonAsync(address, product).Result;

                if (!response.IsSuccessStatusCode)
                    createSuccess = false;
            }

            return Json(createSuccess, JsonRequestBehavior.AllowGet);
        }
 

接著,來到Index View頁面中添加4個textbox用來輸入Product Name,Count,Price,Description的信息以及一個Create Product按鈕。

 
    <div style="background-color: #CA5100; padding: 10px; margin: 5px; width: 45%;">
        <div style="font-weight:bold;margin-bottom:5px;">Create Product</div>
        <div>
            <table>
                <tr><td> Product Name:</td><td><input id="txtCreateProductName" name="txtCreateProductName" type="text" /></td></tr>
                <tr><td>Count:</td><td><input id="txtCreateCount" name="txtCreateCount" type="text" /></td></tr>
                <tr><td> Price:</td><td><input id="txtCreatePrice" name="txtCreatePrice" type="text" /></td></tr>
                <tr><td> Description:</td><td><input id="txtCreateDescription" name="txtCreateDescription" type="text" /></td></tr>
            </table>
        </div>
        <div>
            <div id="createMessage" style="color:blue;"></div>
            <input id="btnCreateProduct" name="btnCreateProduct" type="button" value="Create Product" />
        </div>
    </div>
 

為按鈕Create Produc按鈕t添加Ajax方法

 
        $('#btnCreateProduct').click(function () {
            if ($('#txtCreateProductName').val().trim() != "" && $('#txtCreateCount').val().trim() != "" &&
                $('#txtCreatePrice').val().trim() != "" && $('#txtCreateDescription').val().trim() != "") {
                var product = {
                    ProductID: 0, ProductName: $('#txtCreateProductName').val(),
                    Count: $('#txtCreateCount').val(), Price: $('#txtCreatePrice').val(),
                    Description: $('#txtCreateDescription').val()
                };

                $.ajax({
                    url: '/Product/CreateProduct',
                    type: 'GET',
                    data: product,
                    dataType: 'json'
                }).success(function (result) {
                    if (result != null && result) {
                        $('#createMessage').html('Product create success.');
                        $("#btnGetProductList").trigger('click');
                    }
                }).error(function (data) {
                    alert(data);
                })
            }
        });
 

運行程序,加載Product列表。

點擊Create Product按鈕之前:

通過HttpClient 調(diào)用ASP.NET Web API示例

輸入新增數(shù)據(jù),點擊Create Product按鈕之后:

通過HttpClient 調(diào)用ASP.NET Web API示例

我們看到新增數(shù)據(jù)成功并顯示到了Product列表中。

 

4.修改Product信息

這里我們創(chuàng)建5個textbox,用來輸入Product ID,Product Name,Count,Price,Description的信息以及一個Update Product按鈕。

首先,我們先完成在ProductController中使用HttpClient調(diào)用Web API中修改一條Product數(shù)據(jù)的方法。

 
        public JsonResult UpdateProduct(Product product)
        {
            bool updateSuccess = true;
            Uri address = new Uri(_baseAddress, "/api/products");

            using (var httpClient = new HttpClient())
            {
                var response = httpClient.PutAsync<Product>(address, product, new JsonMediaTypeFormatter()).Result;

                if (!response.IsSuccessStatusCode)
                    updateSuccess = false;
            }

            return Json(updateSuccess, JsonRequestBehavior.AllowGet);
        }
 

接著,來到Index View頁面中添加5個textbox用來輸入Product ID,Product Name,Count,Price,Description的信息以及一個Update Product按鈕。

 
    <div style="background-color: #007ACC; padding: 10px; margin: 5px; width: 45%;">
        <div style="font-weight:bold;margin-bottom:5px;">Update Product</div>
        <div>
            <table>
                <tr><td>Product ID:</td><td><input id="txtUpdateProductID" name="txtUpdateProductID" type="text" /></td></tr>
                <tr><td> Product Name:</td><td><input id="txtUpdateProductName" name="txtUpdateProductName" type="text" /></td></tr>
                <tr><td>Count:</td><td><input id="txtUpdateCount" name="txtUpdateCount" type="text" /></td></tr>
                <tr><td> Price:</td><td><input id="txtUpdatePrice" name="txtUpdatePrice" type="text" /></td></tr>
                <tr><td> Description:</td><td><input id="txtUpdateDescription" name="txtUpdateDescription" type="text" /></td></tr>
            </table>
        </div>
        <div>
            <div id="updateMessage" style="color:white;"></div>
            <input id="btnUpdateProduct" name="btnUpdateProduct" type="button" value="Update Product" />
        </div>
    </div>
 

為按鈕Update Product按鈕添加Ajax方法

 
      $('#btnUpdateProduct').click(function () {
            if ($('#txtUpdateProductID').val().trim() != "" && $('#txtUpdateProductName').val().trim() != "" &&
                $('#txtUpdateCount').val().trim() != "" && $('#txtUpdatePrice').val().trim() != null && $('#txtUpdateDescription').val().trim() != "") {
                var product = {
                    ProductID: $('#txtUpdateProductID').val(), ProductName: $('#txtUpdateProductName').val(),
                    Count: $('#txtUpdateCount').val(), Price: $('#txtUpdatePrice').val(),
                    Description: $('#txtUpdateDescription').val()
                };

                $.ajax({
                    url: '/Product/UpdateProduct',
                    type: 'GET',
                    data: product,
                    dataType: 'json'
                }).success(function (result) {
                    if (result != null && result) {
                        $('#updateMessage').html('Product update success.');
                        $('#btnGetProductList').trigger('click');
                    }
                }).error(function (data) {
                    alert(data);
                })
            }
        });
 

運行代碼,加載Product列表。
點擊Update Create按鈕之前:

通過HttpClient 調(diào)用ASP.NET Web API示例

這里我們修改第一條數(shù)據(jù),輸入修改信息,點擊Update Product按鈕之后:

通過HttpClient 調(diào)用ASP.NET Web API示例

我們看到Product ID1的信息成功修改并顯示到了Product列表中。

 

5.刪除Product

這里我們創(chuàng)建1個textbox,用來輸入Product ID的信息以及一個Delete Product按鈕。

首先,我們先完成在ProductController中使用HttpClient調(diào)用Web API中刪除一條Product數(shù)據(jù)的方法。

 
        public JsonResult DeleteProduct(int id)
        {
            bool deleteSuccess = true;
            Uri address = new Uri(_baseAddress, "/api/products/" + id);

            using (var httpClient = new HttpClient())
            {
                var response = httpClient.DeleteAsync(address).Result;

                if (!response.IsSuccessStatusCode)
                    deleteSuccess = false;
            }

            return Json(deleteSuccess, JsonRequestBehavior.AllowGet);
        }
 

接著,來到Index View頁面中添加1個textbox用來輸入Product ID的信息以及一個Delete Product按鈕。

 
    <div style="background-color: #B572BA; padding: 10px; margin: 5px; width: 45%; ">
        <div style="font-weight:bold;margin-bottom:5px;">Delete Product</div>
        <div>Product ID:&nbsp;<input id="txtDeleteProductID" name="txtDeleteProductID" type="text" />&nbsp;<input id="btnDeleteProduct" name="btnDeleteProduct" type="button" value="Delete Prdouct" /></div>
        <div id="deleteMessage" style="color:blue;"></div>
    </div>
 

為按鈕Delete Product按鈕添加Ajax方法

 
       $('#btnDeleteProduct').click(function () {
            if ($('#txtDeleteProductID').val().trim() != "") {
                $.ajax({
                    url: '/Product/DeleteProduct?id=' + $('#txtDeleteProductID').val(),
                    type: 'GET',
                    dataType: 'json'
                }).success(function (result) {
                    if (result != null && result) {
                        $('#deleteMessage').html('Product delete success.');
                        $('#btnGetProductList').trigger('click');
                    }
                }).error(function (data) {
                    alert(data);
                })
            }
        });
 

運行代碼,加載Product列表。
點擊Delete Product按鈕之前。

通過HttpClient 調(diào)用ASP.NET Web API示例

這里我們輸入Product ID為1的數(shù)據(jù),點擊Delete Product按鈕之后:

通過HttpClient 調(diào)用ASP.NET Web API示例

我們看到Product ID1的數(shù)據(jù)成功刪除,并且Product列表中也沒有了這條數(shù)據(jù)。

好了,本篇就先到此,希望對你有所幫助,謝謝!

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:http://www.cnblogs.com/mejoy/p/6439803.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 色色色色色色网 | 9久热久爱免费精品视频在线观看 | 天使萌痴汉在线中文字幕 | 男人天堂色 | 蛮荒的童话未删减在线观看 | 日韩在线第一区 | 青青网站 | 女bbwxxxx非洲黑人 | 婷婷影院在线观看 | 32d乳白色的奶罩未删除 | 国产成人免费在线视频 | 天天舔天天干天天操 | 无人在线视频高清免费观看动漫 | 99久久精品免费看国产高清 | 翁息肉小说老扒 | 国产欧美日韩精品一区二 | 亚裔aⅴ艳星katsuni | 99久久精品免费看国产一区 | 国产在线影院 | 日韩欧美一级大片 | 国产精品久久久久a影院 | 亚洲日韩男人网在线 | 亚洲精品国产成人99久久 | 暖暖影院日本版 | 久久视频在线视频观看天天看视频 | chinaese中国女人厕所小便 | 欧美激情 亚洲 | 亚洲精品动漫免费二区 | 久久视热频国产这里只有精品23 | 免费网站看v片在线成人国产系列 | 亚洲第一网色综合久久 | 成人伊人青草久久综合网破解版 | 国产一页 | 乌克兰18sex性hd | 亚洲瑟瑟网 | 国产免费好大好硬视频 | 欧美日韩中文字幕一区二区高清 | 欧美性一区二区三区 | 日本在线看 | 国产高清小视频 | 午夜理论片YY4399影院 |