日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

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

發(fā)布時間:2025/3/21 asp.net 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java调用asp.net webapi_通过HttpClient 调用ASP.NET Web API示例 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

在前面兩篇文章中我們介紹了ASP.NET Web API的基本知識和原理,并且通過簡單的實例了解了它的基本(CRUD)操作。我們是通過JQuery和Ajax對Web API進(jìn)行數(shù)據(jù)操作。這一篇我們來介紹一下使用HttpClient的方式來對Web API進(jìn)行數(shù)據(jù)操作。

這里我們還是繼續(xù)使用對Product的操作實例來演示一下它的基本應(yīng)用。

創(chuàng)建ASP.NET Web API應(yīng)用程序

在VS中選擇創(chuàng)建一個ASP.NET Web Application應(yīng)用程序,在向?qū)У南乱粋€窗口中選擇Web API模板。

創(chuàng)建Model

這里我們在Models文件夾下創(chuàng)建一個簡單的Product model類,用來傳遞數(shù)據(jù)。

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

}

創(chuàng)建Cotroller

接著在Controllers文件夾下創(chuàng)建一個API Controller, 命名為"ProductsController"。

在Controllers文件夾上點擊右鍵,選擇Add -> Controller ,在彈出向?qū)е羞x擇Web API 2 Controller - Empty

在向?qū)乱徊街休斎階PI Controller name為"ProductsController"。

因為我們需要通過HttpClient的方式來調(diào)用Web API,所以這里我們還需要創(chuàng)建一個MVC Controller。

同樣在Controllers文件夾上點擊右鍵,選擇Add -> Controller ,在彈出向?qū)е羞x擇MVC 5 Controller - Empty

在向?qū)乱徊街休斎隡VC 5 Controller name為"ProductController"。

創(chuàng)建Web API方法(CRUD)

這里我們依然使用模擬的數(shù)據(jù)創(chuàng)建簡單的CRUD Web API方法。前面的章節(jié)有詳細(xì)講解到,這里就不細(xì)說了。直接上代碼。

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調(diào)用MVC Controller,在MVC Controller中通過HttpClient調(diào)用Web API

Web API中的(CRUD)方法創(chuàng)建完成,接下來我們就分別來看看對各個方法的數(shù)據(jù)操作。

1.獲取Product列表

打開我們創(chuàng)建好的MVC 5 Controller文件ProductController。使用HttpClient的方式來調(diào)用我們Web API中的列表方法。

首先需要引入System.Net.Http

using System.Net.Http;

接下來為我們的Web API地址定義一個公共靜態(tài)變量。

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調(diào)用來獲取Product列表數(shù)據(jù),所以這里我們使用JsonResult返回數(shù)據(jù)。

接下來,我們就來創(chuàng)建View。

文件夾Views->Product下創(chuàng)建一個View,名為"Index"。打開Index View,修改頁面代碼如下:

@{

Layout = null;

}

IndexGet Product List

接著,我們要做的是,當(dāng)點擊Get Product List按鈕是加載Product List,代碼實現(xiàn)如下:

$('#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數(shù)據(jù)列表加載成功。

2.獲取單條Product數(shù)據(jù)

這里我們的做法是在搜索框里輸入Product ID,然后點擊Get Product按鈕,查找出這條Product信息。

首先,我們先完成在ProductController中使用HttpClient調(diào)用Web API中獲取單條Product數(shù)據(jù)的方法。

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 ProductProduct 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的數(shù)據(jù)

我們看到Product ID為1的數(shù)據(jù)成功獲取。

3.新增一條Product

這里我們創(chuàng)建4個textbox,用來輸入Product Name,Count,Price,Description的信息以及一個Create Product按鈕。

首先,我們先完成在ProductController中使用HttpClient調(diào)用Web API中新增一條Product數(shù)據(jù)的方法。

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按鈕之前:

輸入新增數(shù)據(jù),點擊Create Product按鈕之后:

我們看到新增數(shù)據(jù)成功并顯示到了Product列表中。

4.修改Product信息

這里我們創(chuàng)建5個textbox,用來輸入Product ID,Product Name,Count,Price,Description的信息以及一個Update Product按鈕。

首先,我們先完成在ProductController中使用HttpClient調(diào)用Web API中修改一條Product數(shù)據(jù)的方法。

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按鈕之前:

這里我們修改第一條數(shù)據(jù),輸入修改信息,點擊Update Product按鈕之后:

我們看到Product ID為1的信息成功修改并顯示到了Product列表中。

5.刪除Product

這里我們創(chuàng)建1個textbox,用來輸入Product ID的信息以及一個Delete Product按鈕。

首先,我們先完成在ProductController中使用HttpClient調(diào)用Web API中刪除一條Product數(shù)據(jù)的方法。

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 ProductProduct 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的數(shù)據(jù),點擊Delete Product按鈕之后:

我們看到Product ID為1的數(shù)據(jù)成功刪除,并且Product列表中也沒有了這條數(shù)據(jù)。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

總結(jié)

以上是生活随笔為你收集整理的java调用asp.net webapi_通过HttpClient 调用ASP.NET Web API示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。