没有合适的资源?快使用搜索试试~ 我知道了~
【ASP.NET编程知识】通过HttpClient 调用ASP.NET Web API示例.docx
2 下载量 32 浏览量
2023-05-21
21:12:09
上传
评论
收藏 248KB DOCX 举报
温馨提示
试读
35页
【ASP.NET编程知识】通过HttpClient 调用ASP.NET Web API示例.docx
资源推荐
资源详情
资源评论
全文可编辑 word 文档 页眉与背景水印可删除
1
通过 HttpClient 调用 ASP.NET Web API 示例
在前面两篇文章中我们介绍了 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
全文可编辑 word 文档 页眉与背景水印可删除
2
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
全文可编辑 word 文档 页眉与背景水印可删除
3
在 向 导 下 一 步 中 输 入 API Controller name 为
"ProductsController"。
因为我们需要通过 HttpClient 的方式来调用 Web API,
所以这里我们还需要创建一个 MVC Controller。
同样在 Controllers 文件夹上点击右键,选择 Add ->
Controller ,在弹出向导中选择 MVC 5 Controller - Empty
全文可编辑 word 文档 页眉与背景水印可删除
4
在 向 导 下 一 步 中 输 入 MVC 5 Controller name 为
"ProductController"。
创建 Web API 方法(CRUD)
这里我们依然使用模拟的数据创建简单的 CRUD Web API
方法。前面的章节有详细讲解到,这里就不细说了。直接上
代码。
public class ProductsController : ApiController
{
// Mock product list
public static List<Product> productList =
initProductMockDataList();
全文可编辑 word 文档 页眉与背景水印可删除
5
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"},
剩余34页未读,继续阅读
资源评论
mmoo_python
- 粉丝: 0
- 资源: 1万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功