在前面两篇文章中我们介绍了 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 productList = initProductMockDataList();
- private static List initProductMockDataList() {
- return new List() {
- 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 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 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>().Result;
- }
- return Json(productList, JsonRequestBehavior.AllowGet);
- }
这里我们需要通过点击按钮,通过 Ajax 调用来获取 Product 列表数据,所以这里我们使用 JsonResult 返回数据。
接下来,我们就来创建 View。
文件夹 Views->Product 下创建一个 View, 名为 "Index"。打开 Index View, 修改页面代码如下:
- @{
- Layout = null;
- }
- "viewport" content="width=device-width" />
- "~/Scripts/jquery-1.10.2.min.js" type="text/javascript">
- "background-color: #008000; padding: 10px; margin: 5px; width: 45%;">
- "font-weight: bold; margin-bottom: 5px;">Get Product List
- "padding-bottom:5px;">"btnGetProductList" name="btnGetProductList" type="button" value="Get Product List" />
- "products">
接着,我们要做的是,当点击 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().Result;
- }
- return Json(product, JsonRequestBehavior.AllowGet);
- }
接着,来到 Index View 页面中添加一个搜索 Product ID 的 textbox 以及一个 Get Product 的按钮。
- "background-color: #9ACD32; padding: 10px; margin: 5px; width: 45%; ">
- "font-weight:bold;margin-bottom:5px;">Get Single Product
- Product ID: "txtSearchProductID" name="txtSearchProductID" type="text" /> "btnGetProduct" name="btnGetProduct" type="button" value="Get Prdouct" />
- "product">
为按钮 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 按钮。
- "background-color: #CA5100; padding: 10px; margin: 5px; width: 45%;">
- "font-weight:bold;margin-bottom:5px;">Create Product
- Product Name:
- "txtCreateProductName" name="txtCreateProductName" type="text" />
- Count:"txtCreateCount" name="txtCreateCount" type="text" />
- Price:"txtCreatePrice" name="txtCreatePrice" type="text" />
- Description:"txtCreateDescription" name="txtCreateDescription" type="text" />
- "createMessage" style="color:blue;">
- "btnCreateProduct" name="btnCreateProduct" type="button" value="Create Product" />
为按钮 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(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 按钮。
- "background-color: #007ACC; padding: 10px; margin: 5px; width: 45%;">
- "font-weight:bold;margin-bottom:5px;">Update Product
- Product ID:
- "txtUpdateProductID" name="txtUpdateProductID" type="text" />
- Product Name:"txtUpdateProductName" name="txtUpdateProductName" type="text" />
- Count:"txtUpdateCount" name="txtUpdateCount" type="text" />
- Price:"txtUpdatePrice" name="txtUpdatePrice" type="text" />
- Description:"txtUpdateDescription" name="txtUpdateDescription" type="text" />
- "updateMessage" style="color:white;">
- "btnUpdateProduct" name="btnUpdateProduct" type="button" value="Update Product" />
为按钮 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 按钮。
- "background-color: #B572BA; padding: 10px; margin: 5px; width: 45%; ">
- "font-weight:bold;margin-bottom:5px;">Delete Product
- Product ID: "txtDeleteProductID" name="txtDeleteProductID" type="text" /> "btnDeleteProduct" name="btnDeleteProduct" type="button" value="Delete Prdouct" />
- "deleteMessage" style="color:blue;">
为按钮 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 列表中也没有了这条数据。
好了,本篇就先到此,希望对你有所帮助,谢谢!
来源: http://www.cnblogs.com/mejoy/p/6439803.html