• <fieldset id="8imwq"><menu id="8imwq"></menu></fieldset>
  • <bdo id="8imwq"><input id="8imwq"></input></bdo>
    最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
    問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
    當前位置: 首頁 - 科技 - 知識百科 - 正文

    通過HttpClient 調用ASP.NET Web API示例

    來源:懂視網 責編:小采 時間:2020-11-27 22:35:58
    文檔

    通過HttpClient 調用ASP.NET Web API示例

    通過HttpClient 調用ASP.NET Web API示例:在前面兩篇文章中我們介紹了ASP.NET Web API的基本知識和原理,并且通過簡單的實例了解了它的基本(CRUD)操作。我們是通過JQuery和Ajax對Web API進行數據操作。這一篇我們來介紹一下使用HttpClient的方式來對Web API進行數據操作。 這里我們還是繼續使
    推薦度:
    導讀通過HttpClient 調用ASP.NET Web API示例:在前面兩篇文章中我們介紹了ASP.NET Web API的基本知識和原理,并且通過簡單的實例了解了它的基本(CRUD)操作。我們是通過JQuery和Ajax對Web API進行數據操作。這一篇我們來介紹一下使用HttpClient的方式來對Web API進行數據操作。 這里我們還是繼續使

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

    這里我們還是繼續使用對Product的操作實例來演示一下它的基本應用。

     創建ASP.NET Web API應用程序

    在VS中選擇創建一個ASP.NET Web Application應用程序,在向導的下一個窗口中選擇Web API模板。

     創建Model

    這里我們在Models文件夾下創建一個簡單的Product model類,用來傳遞數據。

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

    創建Cotroller

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

    在Controllers文件夾上點擊右鍵,選擇Add -> Controller ,在彈出向導中選擇Web API 2 Controller - Empty

    在向導下一步中輸入API Controller name為"ProductsController"。

    因為我們需要通過HttpClient的方式來調用Web API,所以這里我們還需要創建一個MVC Controller。

    同樣在Controllers文件夾上點擊右鍵,選擇Add -> Controller ,在彈出向導中選擇MVC 5 Controller - Empty

    在向導下一步中輸入MVC 5 Controller name為"ProductController"。

    創建Web API方法(CRUD)

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

     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調用MVC Controller,在MVC Controller中通過HttpClient調用Web API

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

    1.獲取Product列表

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

    首先需要引入System.Net.Http

    using System.Net.Http;

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

    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調用來獲取Product列表數據,所以這里我們使用JsonResult返回數據。

    接下來,我們就來創建View。

    文件夾Views->Product下創建一個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,代碼實現如下:

     $('#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按鈕之前如下:

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

    Product數據列表加載成功。

     2.獲取單條Product數據

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

    首先,我們先完成在ProductController中使用HttpClient調用Web API中獲取單條Product數據的方法。

     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 ID的textbox以及一個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: <input id="txtSearchProductID" name="txtSearchProductID" type="text" /> <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按鈕前:

    這里我們查找Product ID為1的數據

    我們看到Product ID為1的數據成功獲取。

     3.新增一條Product

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

    首先,我們先完成在ProductController中使用HttpClient調用Web API中新增一條Product數據的方法。

     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按鈕之前:

    輸入新增數據,點擊Create Product按鈕之后:

    我們看到新增數據成功并顯示到了Product列表中。

     4.修改Product信息

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

    首先,我們先完成在ProductController中使用HttpClient調用Web API中修改一條Product數據的方法。

     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按鈕之前:

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

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

     5.刪除Product

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

    首先,我們先完成在ProductController中使用HttpClient調用Web API中刪除一條Product數據的方法。

     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: <input id="txtDeleteProductID" name="txtDeleteProductID" type="text" /> <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按鈕之前。

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

    我們看到Product ID為1的數據成功刪除,并且Product列表中也沒有了這條數據。

    聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

    文檔

    通過HttpClient 調用ASP.NET Web API示例

    通過HttpClient 調用ASP.NET Web API示例:在前面兩篇文章中我們介紹了ASP.NET Web API的基本知識和原理,并且通過簡單的實例了解了它的基本(CRUD)操作。我們是通過JQuery和Ajax對Web API進行數據操作。這一篇我們來介紹一下使用HttpClient的方式來對Web API進行數據操作。 這里我們還是繼續使
    推薦度:
    標簽: API 示例 實例
    • 熱門焦點

    最新推薦

    猜你喜歡

    熱門推薦

    專題
    Top
    主站蜘蛛池模板: 精品精品国产理论在线观看| 99久久久精品免费观看国产| 丰满人妻熟妇乱又伦精品劲| 久久国产精品国语对白| 特级精品毛片免费观看| 久久青青草原精品影院| 亚洲欧美精品AAAAAA片| 国产精品无码不卡一区二区三区| 97久视频精品视频在线老司机| 欧美人与性动交α欧美精品成人色XXXX视频| 香港aa三级久久三级老师2021国产三级精品三级在 | 2022精品天堂在线视频| 精品乱码久久久久久夜夜嗨| 蜜臀久久99精品久久久久久小说| 国产精品久久久久久福利漫画| 999国产精品视频| 久久国产热精品波多野结衣AV| 亚洲综合精品一二三区在线| 精品一区二区三区免费观看| 亚洲日韩精品无码专区网址| 久久精品亚洲一区二区三区浴池| 国产精品亚洲一区二区在线观看| 99精品热这里只有精品| 人人妻人人澡人人爽人人精品电影 | 久久国产精品无码HDAV| 久久久久久国产精品无码超碰| 久久精品国产91久久麻豆自制 | 国产亚洲精品无码拍拍拍色欲| 亚洲av午夜成人片精品网站| 欧美亚洲国产精品久久蜜芽| 久久996热精品xxxx| 97精品久久天干天天天按摩| 欧美精品区一级片免费播放| 国产精品网址你懂的| 无码久久精品国产亚洲Av影片| 国产成人精品一区二三区在线观看| 无码精品国产一区二区三区免费 | 久久精品国产福利国产琪琪| 国产亚洲美女精品久久久久狼| 无码人妻精品一区二区三区66 | 日韩精品一二三四区|