Use HttpClient to call ASP. NET Web API example, httpclientapi

Source: Internet
Author: User

Use HttpClient to call ASP. NET Web API example, httpclientapi

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

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

 Create an ASP. NET Web API application

In VS, create an ASP. NET Web Application, and select a Web API template in the next window of the wizard.

Create Model

Here we create a simple Product model class under the Models folder to transfer data.

Right-click the Models folder and choose 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

Create an API Controller in the Controllers folder and name it "ProductsController ".

Right-click the Controllers folder and choose Add-> Controller. In the displayed wizard, select Web API 2 Controller-Empty.

In the next step of the wizard, enter the API Controller name as "ProductsController ".

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

Also, right-click the Controllers folder and choose Add> Controller. In the displayed wizard, select MVC 5 Controller-Empty.

In the next step of the wizard, enter the MVC 5 Controller name as "ProductController ".

Create a Web API (CRUD)

Here we still use the simulated data to create a simple CRUD Web API method. The previous sections will be explained in detail, so we will not detail them here. Directly add 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, and call Web API through HttpClient in MVC Controller

The (CRUD) method in the Web API is created. Next, let's take a look at the data operations on each method.

1. Get the Product list

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

First, introduce System. Net. Http

using System.Net.Http;

Next, 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 click the button to obtain the Product list data through Ajax call, so here we use JsonResult to return data.

Next, we will create a View.

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

@{  Layout = null;}<!DOCTYPE html>

Next, we need to load the Product List by clicking the Get Product List button. The code implementation is as follows:

    $('#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);    }

Okay. Run the code.

Before clicking the Get Product List button:

Click Get Product List as follows:

The Product data list is loaded successfully.

2. Get Single Product Data

Here, we enter the Product ID in the search box and click Get Product to find the Product information.

First, we need to call the Web API to obtain a single Product data in ProductController using HttpClient.

    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 to search for the Product ID and a Get Product button.

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

Add Ajax method for the Get Product button

    $('#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);        });      }    });

Run the program and load the Product list.

Before clicking Get Product:

Here we look for the data with the Product ID 1

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

3. Add a Product

Here we Create four textbox for entering the Product Name, Count, Price, Description information and a Create Product button.

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

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

Next, add four textbox entries to the Index View page to enter the Product Name, Count, Price, Description information and a Create Product button.

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

Add Ajax Method for button Create Produc button t

    $('#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);        })      }    });

Run the program and load the Product list.

Before clicking the Create Product button:

Enter new data and click Create Product:

We can see that the new data is successfully added and displayed in the Product list.

4. modify Product information

Here we create five textbox to enter the Product ID, Product Name, Count, Price, Description information and an Update Product button.

First, we need to use HttpClient in ProductController to call the Web API to modify a Product data.

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

Next, add five textbox entries to the Index View page to enter the Product ID, Product Name, Count, Price, Description information, and an Update Product button.

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

Add Ajax method for the Update Product button

   $('#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);        })      }    });

Run the code to load the Product list.

Before clicking the Update Create button:

Here we modify the first data, enter the modification information, and click the Update Product button:

We can see that the Product ID is successfully modified and displayed in the Product list.

5. Delete Product

Here we create a textbox to enter the Product ID information and a Delete Product button.

First, we will call the Web API in ProductController to delete a Product data using HttpClient.

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

On the Index View page, add a textbox to enter the Product ID information and a Delete Product button.

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

Add Ajax method for the Delete Product button

   $('#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);        })      }    });

Run the code to load the Product list.

Click Delete Product.

Here we enter the data with the Product ID 1 and click the Delete Product button:

We can see that the data with the Product ID 1 is successfully deleted, and this data is not found in the Product list.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.