HttpClient calling the ASP.

Source: Internet
Author: User
This article mainly introduces the example of calling ASP. NET Web API through HttpClient, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

In the previous two articles, we introduced the basics and principles of the ASP, and learned its basic (CRUD) operations through a simple example. We do data manipulation of the Web API through jquery and Ajax. Let's take a look at using httpclient to perform data manipulation on the Web API.

Here we continue to use an example of product operation to demonstrate its basic application.

creating an ASP. NET WEB API application

Select Create an ASP. NET Web application application in VS and select the 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 pass the 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

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

Right-click on the Controllers folder, select Add, Controller, select Web API 2 in the popup wizard Controller-empty

Enter the API Controller name "ProductsController" in the next step of the wizard.

Because we need to invoke the Web API in a httpclient way, we also need to create an MVC Controller here.

Also right-click on the Controllers folder, select Add-and Controller, select MVC 5 in the popup wizard Controller-empty

Enter MVC 5 Controller name "Productcontroller" in the next step of the wizard.

Creating a Web API method (CRUD)

Here we still use the simulated data to create a simple CRUD Web API approach. The previous chapters are explained in detail, and this is not the case. directly on the code.

  public class Productscontroller:apicontroller {//Mock product list public static list<product> Productl    ist = 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 {Produ Ctid=2,productname= "Product B", price=200000,count=2,description= "Description B"}, new Product {productid=3,productn Ame= "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,c    ount=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.produ CtID).      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 = = pr Oduct. 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 the MVC controller through jquery and Ajax and invoke the Web API through httpclient in the MVC controller

The Web API (CRUD) method is created, and then we look at the data operations for each method separately.

1. Get the Product List

Open the MVC 5 controller file we created Productcontroller. Use HttpClient to invoke the list method in our Web API.

First, we need to 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 get the product list data by clicking the button and using AJAX calls, so here we use Jsonresult to return the data.

Next, we'll create the view.

Under Folder Views->product, create a view named "Index". Open the index View and modify the page code as follows:

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

Next, what we want to do is, when clicking the Get Product List button is loading the product list, the code is implemented 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 ' cell      spacing= ' 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.

Click the Get Product List button before the following:

Click the Get Product List button after the following:

The product data list was loaded successfully.

2. Get a single product data

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

First, we will first complete the method of getting the single product data in the Productcontroller using the HttpClient call Web API.

    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, come to the Index view page to add a textbox that searches for the product ID and a button for get product.

  <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 an Ajax method for the button 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 the Get Product button:

Here we look for data with Product ID 1

We see a successful acquisition of the data with Product ID 1.

3. Add an article product

Here we create 4 textbox, which is used to enter the information of product name,count,price,description and a Create product button.

First, we will first complete the method of adding a new product data to the Web API using HttpClient in Productcontroller.

    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, go to the Index view page to add 4 textbox information to input product name,count,price,description and a Create product button.

  <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&gt ; <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=" TxtCr    Eatedescription "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> 

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:

After entering the new data, click the Create Product button:

We saw that the new data was successful and displayed in the Product list.

4. Modifying product information

Here we create 5 textbox to enter the information for Product id,product name,count,price,description and an Update product button.

First, we first complete the method of modifying a product data in the Productcontroller using the HttpClient call Web API.

    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, come to the Index view page and add 5 textbox to enter the information for Product id,product name,count,price,description and an Update product button.

  <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:&LT;/TD&GT;&LT;TD&GT;&L T;input id= "Txtupdateproductid" name= "Txtupdateproductid" type= "text"/></td></tr> <tr><td& Gt 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 I D= "Txtupdateprice" name= "Txtupdateprice" type= "text"/></td></tr> <tr><td> description:& Lt;/td><td><input id= "txtupdatedescription" name= "txtupdatedescription" type= "text"/></td> </tr> &LT;/TABLE&GT </p> <p> <p id= "updatemessage" style= "color:white;"    ></p> <input id= "btnupdateproduct" name= "btnupdateproduct" type= "button" value= "Update Product"/> </p> </p>

Add an Ajax method for the button Update product button

   $ (' #btnUpdateProduct '). Click (function () {if ($ (' #txtUpdateProductID '). Val (). Trim ()! = "" && $ (' #txtUpdat Eproductname '). Val (). Trim ()! = "" && $ (' #txtUpdateCount '). Val (). Trim ()! = "" && $ (' #txtUpdatePrice ' ). Val (). Trim ()! = NULL && $ (' #txtUpdateDescription '). Val (). Trim ()! = "") {var product = {Product ID: $ (' #txtUpdateProductID '). Val (), ProductName: $ (' #txtUpdateProductName '). Val (), Count: $ (' #txtUpdateCount '). VA        L (), 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, click on the Update Product button:

We saw that the information for Product ID 1 was successfully modified and displayed in the Product list.

5. Delete Product

Here we create 1 textbox, which is used to enter the product ID information and a Delete product button.

First, we first complete the method of deleting a product data in the Productcontroller using the HttpClient call Web API.

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

Next, come to the Index view page and add 1 textbox information to enter the product ID and a Delete product button.

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

Add an Ajax method for the button 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.

Before clicking the Delete Product button.

Here we enter data with Product ID 1, after clicking the Delete product button:

We saw that the data with Product ID 1 was successfully deleted, and this data is not in the product list.

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.