在前面两篇文章中我们介绍了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;

}

Index

Get Product List

接着,我们要做的是,当点击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 = $("

");

var productTableTitle = $("

Product IDProduct NamePriceCountDescription");

productTableTitle.appendTo(productTable);

for (var i = 0; i < result.length; i++) {

var productTableContent = $("

"

+ result[i].ProductID + "

"

+ result[i].ProductName + "

"

+ result[i].Price + "

"

+ result[i].Count + "

"

+ result[i].Description + "

");

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的按钮。

Get Single Product
Product ID:  

为按钮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 + "
" + "Product Name: " + result.ProductName + "
" + "Count: " + result.Count + "
" + "Price: " + result.Price + "
" + "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按钮。

Create Product
Product Name:
Count:
Price:
Description:

为按钮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按钮。

Update Product
Product ID:
Product Name:
Count:
Price:
Description:

为按钮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按钮。

Delete Product
Product ID:  

为按钮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列表中也没有了这条数据。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

java调用asp.net webapi_通过HttpClient 调用ASP.NET Web API示例相关推荐

  1. 返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 Web API

    返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 Web API 原文:返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 ...

  2. 在Asp.net应用程序中构建基于WCF Web.Api的服务

    WCF Web API Preview 5 发布了,你可以官方网站下载或通过Nuget安装它. 下面让我们在Asp.net applicatoin中来实现一个非常简单的web api service. ...

  3. 图灵机器人php调用案例,使用httpclient实现图灵机器人web api调用实例

    本人在使用图灵机器人的过程中,发现很不错,想试了通过api请求来获取回复,这样可以做一个页面聊天还是很不错的.网上搜到的文章好多都是get接口,现在已经不能用了,也不用urlencodeer方法处理i ...

  4. 使用Swagger,ApiExplorer和NSwag掌握ASP.NET Core和ABP中的外部Web API

    目录 更多Cowbell Swagger 探索ApiExplorer 消费Swagger ...没那么快 最后的技巧和窍门 结论 该博客条目通过向我现有的Web应用程序中添加第二个swagger文件, ...

  5. java wed高德地图开发_java接入高德地图常用WEB API

    1.先看一下高德地图WEB API都有哪些内容 2.根据经经纬度查询高德地图省市区数据 /** *根据经纬度获取省市区 * @param lat * @return */ public static ...

  6. 怎么看调用的接口_SpringCloud服务间调用

    本篇简介 在上一篇我们介绍了SpringCloud中的注册中心组件Eureka.Eureka的作用是做服务注册与发现的,目的是让不同的服务与服务之间都可以通过注册中心进行间接关联,并且可以通过注册中心 ...

  7. 使用Entity Framework和Web API的ASP.NET Core Blazor CRUD

    目录 介绍 背景 先决条件 使用代码 第1步--创建数据库和表 第2步--创建ASP.NET Core Blazor应用程序 ASP.NET Core Blazor解决方案的新增功能是什么? 客户端项 ...

  8. Asp.Net Web API 2第一课——入门

    前言 Http不仅仅服务于Web Pages.它也是一个创建展示服务和数据的API的强大平台.Http是简单的.灵活的.无处不在的.你能想象到几乎任何的平台都会有HTTP服务库.HTTP服务可以涉及到 ...

  9. ASP.NET Core:从ASP.NET Web API迁移的多层数据服务应用程序

    目录 介绍 设置和运行示例应用程序 类库项目 依赖注入 访问应用程序设置 实体框架核心相关更改 主键标识插入问题 数据上下文和连接字符串 自定义存储库(Repositories) LINQ表达式翻新( ...

最新文章

  1. mysql设置定时入伍_mysql 集群自动化配置
  2. php数组函数及用法,php数组函数 in_array 的用法及注意事项
  3. 2.4操作系统之死锁详解(预防、避免、检测、解除)+思维导图
  4. boost::fusion::insert_range用法的测试程序
  5. 使用工具快速找出custom work center使用的ui component
  6. vue 新版本 webpack 代理 跨域设置
  7. 基于Visual C++2013拆解世界五百强面试题--题5-自己实现strstr
  8. python开发web项目_Django2:Web项目开发入门笔记(20)
  9. android studio gradle home,Android Studio3.0 Gradle 4.1配置
  10. android 基本知识
  11. leetcode 349. Intersection of Two Arrays 1
  12. c++语言iso标准,C++20标准 (ISO/IEC 14882:2020) 正式发布
  13. 【财务预警】基于matlab BP神经网络财务预警【含Matlab源码 494期】
  14. OKR案例——不同类型的OKR实例
  15. c语言标准库详解(一):stdio.h之文件操作
  16. Win7中CHM打不开的解决方法
  17. 计算机毕设论文速成——论文思路梳理
  18. X15 - 999、马克思主义基本原理概论、03709
  19. 30岁前,环游世界220天
  20. [每天一个知识点]12-Maven怎么读

热门文章

  1. Linux下Makefile的automake生成全攻略--转
  2. spring事务模板使用
  3. 【Python】写文件个性化设置模块Python_Xlwt练习
  4. 【待继续研究】解析信用评分模型的开发流程及检验标准(晕乎乎,看不懂~)
  5. Hyperledger Fabric Rest API服务开发教程【含源码】
  6. 大数据征信应用与启示 ——以美国互联网金融公司 ZestFinance为例
  7. 携程是如何把大数据用于实时风控的
  8. php如何从左往右轮播,js实现从左向右滑动式轮播图效果
  9. iis 7 php_Windows server 2008 下基于IIS7配置php7.2运行环境
  10. python模块xlwt怎么用不了_python中使用 xlwt 操作excel的常见方法与问题