最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2017年03月07日 11:26:47   作者:MeJoy  
本篇文章主要介紹了通過HttpClient 調(diào)用ASP.NET Web API示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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

 創(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

在向?qū)乱徊街休斎階PI Controller name為"ProductsController"。

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

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

在向?qū)乱徊街休斎隡VC 5 Controller name為"ProductController"。

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

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

  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>

接著,我們要做的是,當(dāng)點擊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);
    }

好了,運(yùn)行代碼。

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

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

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

運(yùn)行程序,加載Product列表。

點擊Get Product按鈕前:

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

我們看到Product ID為1的數(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);
        })
      }
    });

運(yùn)行程序,加載Product列表。

點擊Create Product按鈕之前:

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

我們看到新增數(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);
        })
      }
    });

運(yùn)行代碼,加載Product列表。

點擊Update Create按鈕之前:

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

我們看到Product ID為1的信息成功修改并顯示到了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);
        })
      }
    });

運(yùn)行代碼,加載Product列表。

點擊Delete Product按鈕之前。

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

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

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

相關(guān)文章

  • AspNetCore中的中間件詳解

    AspNetCore中的中間件詳解

    ASP.NET Core處理請求的方式看做是一個管道,中間件是組裝到應(yīng)用程序管道中用來處理請求和響應(yīng)的組件,這篇文章主要介紹了AspNetCore中的中間件詳解,需要的朋友可以參考下
    2023-05-05
  • 如何使用pm2守護(hù)你的.NET Core應(yīng)用程序詳解

    如何使用pm2守護(hù)你的.NET Core應(yīng)用程序詳解

    pm2是nodejs的一個帶有負(fù)載均衡功能的應(yīng)用進(jìn)程管理器的模塊,下面這篇文章主要給大家介紹了關(guān)于如何使用pm2守護(hù)你的.NET Core應(yīng)用程序的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2018-10-10
  • C#實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載客戶端工具類

    C#實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載客戶端工具類

    C#實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載的 Http Web 客戶端工具類 (C# DIY HttpWebClient),感興趣的朋友可以參考下本文,或許對你有所幫助
    2013-04-04
  • 運(yùn)用.net core中實例講解RabbitMQ

    運(yùn)用.net core中實例講解RabbitMQ

    RabbitMQ是實現(xiàn)了高級消息隊列協(xié)議(AMQP)的開源消息代理軟件(亦稱面向消息的中間件),本文詳細(xì)講解了RabbitMQ以及運(yùn)用.net core中實例講解其6中模式,感興趣的小伙伴一起來學(xué)習(xí)吧
    2021-09-09
  • 在GridView中LinkButton的屬性的應(yīng)用(如何不用選中就刪除這一行)

    在GridView中LinkButton的屬性的應(yīng)用(如何不用選中就刪除這一行)

    GridView中LinkButton的屬性的應(yīng)用,實現(xiàn)不用選中就刪除這一行
    2009-04-04
  • linq中的限定操作符

    linq中的限定操作符

    這篇文章介紹了linq中的限定操作符,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-03-03
  • asp.net中session的原理及應(yīng)用詳解

    asp.net中session的原理及應(yīng)用詳解

    Session是一種Web會話中的常用狀態(tài)之一,Session提供了一種把信息保存在服務(wù)器內(nèi)存中的方式。他能儲存任何數(shù)據(jù)類型,包含自定義對象,本文將詳細(xì)介紹asp.net中session的原理及應(yīng)用,需要的朋友可以參考下
    2012-11-11
  • .Net 中WhenAll的解釋和用法小結(jié)

    .Net 中WhenAll的解釋和用法小結(jié)

    在.NET中,WhenAll 是一個與異步編程相關(guān)的擴(kuò)展方法,它屬于 System.Threading.Tasks 命名空間下的 TaskExtensions 類,本文介紹.Net 中WhenAll的解釋和用法,感興趣的朋友跟隨小編一起看看吧
    2024-04-04
  • CHECKBOX 的全選、取消及跨頁保存的實現(xiàn)方法

    CHECKBOX 的全選、取消及跨頁保存的實現(xiàn)方法

    CHECKBOX的操作在頁面中很常見,比如全選、取消、跨頁保存等等,下面有個不錯的示例,大家可以嘗試操作下
    2013-10-10
  • asp.Net JS取母板頁控件值的簡單方法

    asp.Net JS取母板頁控件值的簡單方法

    這篇文章介紹了asp.Net JS取母板頁控件值的簡單方法,有需要的朋友可以參考一下
    2013-07-07

最新評論

玉树县| 内黄县| 洞口县| 资中县| 潍坊市| 博野县| 无为县| 黄龙县| 大余县| 丰原市| 平南县| 久治县| 青龙| 防城港市| 大同市| 密山市| 石楼县| 牙克石市| 温州市| 新巴尔虎左旗| 福安市| 乐至县| 九寨沟县| 梁河县| 滦南县| 会东县| 洞口县| 吕梁市| 周至县| 遂宁市| 鸡西市| 彝良县| 嘉善县| 太白县| 濉溪县| 六盘水市| 冷水江市| 松阳县| 潮安县| 印江| 安福县|