Home  >  Article  >  Backend Development  >  Detailed graphic explanation of HttpClient calling ASP.NET Web API

Detailed graphic explanation of HttpClient calling ASP.NET Web API

Y2J
Y2JOriginal
2017-05-03 13:53:502101browse

This article mainly introduces the example of calling ASP.NET Web API through HttpClient. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look

In the previous two articles, we introduced the basic knowledge and principles of ASP.NET Web API, and learned its basic (CRUD) operations through simple examples. We perform data operations on Web API through JQuery and Ajax. In this article, we will introduce how to use HttpClient to perform data operations on Web API.

Here we will continue to use the operation example of Product to demonstrate its basic application.

Create ASP.NET Web API application

Choose to create an ASP.NET Web Application application in VS, and select Web API in the next window of the wizard template.

Create Model

Here we create a simple Product model class in the Models folder to pass data.

Right-click on the Models folder and select 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; }
  }

Create Cotroller

Then create an API under the Controllers folder Controller, named "ProductsController".

Right-click on the Controllers folder, select Add -> Controller, select Web API 2 Controller - Empty in the pop-up wizard

Under the wizard Enter the API Controller name as "ProductsController" in one step.

Because we need to call the Web API through HttpClient, we also need to create an MVC Controller here.

Similarly right-click on the Controllers folder, select Add -> Controller, and select MVC 5 Controller - Empty in the pop-up wizard

Under the wizard Enter the MVC 5 Controller name as "ProductController" in one step.

Create Web API method (CRUD)

Here we still use simulated data to create a simple CRUD Web API method. This was explained in detail in the previous chapters, so I won’t go into details here. Go directly to the code.

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

Call MVC Controller through JQuery and Ajax, call Web API through HttpClient in MVC Controller

The (CRUD) method in Web API is created, next we Let’s look at the data operations of each method separately.

1. Get the Product list

Open the MVC 5 Controller file ProductController we created. Use HttpClient to call the list method in our Web API.

First we need to introduce System.Net.Http

using System.Net.Http;

Next we define a public static variable for our Web API address.

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

Here we need to get the Product list data by clicking the button and calling Ajax, so here we use JsonResult to return the data.

Next, let’s create View.

Create a View named "Index" under the folder Views->Product. Open the Index View and modify the page code as follows:

@{
  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>
  <p style="background-color: #008000; padding: 10px; margin: 5px; width: 45%;">
    <p style="font-weight: bold; margin-bottom: 5px;">Get Product List</p>
    <p style="padding-bottom:5px;"><input id="btnGetProductList" name="btnGetProductList" type="button" value="Get Product List" /></p>
    <p id="products"></p>
  </p>
  </body>
</html>

Next, what we have to do is to load the Product List when the Get Product List button is clicked. The code is implemented as follows:

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

    // Display product list
    function DisplayProductList(result) {
      var productTable = $("<table cellpadding=&#39;3&#39; cellspacing=&#39;3&#39;></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);
      }

      $(&#39;#products&#39;).html(productTable);
    }

Okay, run code.

Before clicking the Get Product List button, the following is as follows:

After clicking the Get Product List button, the following is as follows:

Product data list is loaded successfully.

2. Obtain a single Product data

What we do here is to enter the Product ID in the search box, and then click the Get Product button to find this Product information.

First, we first complete the method of using HttpClient in the ProductController to call the Web API to obtain a single Product data.

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

Next, go to the Index View page and add a textbox for searching Product ID and a Get Product button.

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

Add Ajax method to the button Get Product button

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

Run the program and load the Product list.

Before clicking the Get Product button:

Here we look for data with Product ID 1

We see that the data with Product ID 1 is successfully obtained.

3. Add a new Product

Here we create 4 textboxes to enter Product Name, Count, Price, Description information and a Create Product button.

首先,我们先完成在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按钮。

  <p style="background-color: #CA5100; padding: 10px; margin: 5px; width: 45%;">
    <p style="font-weight:bold;margin-bottom:5px;">Create Product</p>
    <p>
      <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>
    </p>
    <p>
      <p id="createMessage" style="color:blue;"></p>
      <input id="btnCreateProduct" name="btnCreateProduct" type="button" value="Create Product" />
    </p>
  </p>

为按钮Create Produc按钮t添加Ajax方法

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

        $.ajax({
          url: &#39;/Product/CreateProduct&#39;,
          type: &#39;GET&#39;,
          data: product,
          dataType: &#39;json&#39;
        }).success(function (result) {
          if (result != null && result) {
            $(&#39;#createMessage&#39;).html(&#39;Product create success.&#39;);
            $("#btnGetProductList").trigger(&#39;click&#39;);
          }
        }).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按钮。

  <p style="background-color: #007ACC; padding: 10px; margin: 5px; width: 45%;">
    <p style="font-weight:bold;margin-bottom:5px;">Update Product</p>
    <p>
      <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>
    </p>
    <p>
      <p id="updateMessage" style="color:white;"></p>
      <input id="btnUpdateProduct" name="btnUpdateProduct" type="button" value="Update Product" />
    </p>
  </p>

为按钮Update Product按钮添加Ajax方法

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

        $.ajax({
          url: &#39;/Product/UpdateProduct&#39;,
          type: &#39;GET&#39;,
          data: product,
          dataType: &#39;json&#39;
        }).success(function (result) {
          if (result != null && result) {
            $(&#39;#updateMessage&#39;).html(&#39;Product update success.&#39;);
            $(&#39;#btnGetProductList&#39;).trigger(&#39;click&#39;);
          }
        }).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按钮。

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

为按钮Delete Product按钮添加Ajax方法 

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

运行代码,加载Product列表。

点击Delete Product按钮之前。

这里我们输入Product ID为1的数据,点击Delete Product按钮之后:

我们看到Product ID为1的数据成功删除,并且Product列表中也没有了这条数据。

The above is the detailed content of Detailed graphic explanation of HttpClient calling ASP.NET Web API. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn