创建 ASP.NET Web API 并通过 HTML 客户端使用它 – 第 I 部分






3.29/5 (4投票s)
从头开始创建 ASP.NET Web API 并通过 HTML 客户端使用它。
引言
ASP.NET Web API 是一项非常强大且需求量很高的技术。
今天,我们将讨论创建 ASP.NET Web API 并通过 HTML 客户端使用它。由于本文的篇幅和深度,我将其分成了两部分。在第一部分中,我们的重点是创建 ASP.NET Web API 项目并配置所有必要的内容。而在第二部分中,我们将研究如何使用此 API。
背景
ASP.NET Web API 是一个框架,它使构建 HTTP 服务变得很容易,这些服务可以访问各种客户端,包括浏览器和移动设备。ASP.NET Web API 是在 .NET Framework 上构建 RESTful 应用程序的理想平台。
使用代码
向您的应用程序添加 ASP.NET Web API 控制器几乎与添加 ASP.NET MVC 控制器完全相同。您可以在现有的 MVC 项目中添加 Web API,也可以创建一个单独的 Web API 项目。
让我们开始创建一个新的 Web API 项目。
启动 Visual Studio(在此示例中,我使用了 VS 2012)并按照以下步骤操作
- 选择“新建项目”,然后从项目模板列表中选择“ASP.NET MVC 4 Web 应用程序”。将项目命名为“WebApiDemo”。
- 在“项目模板”对话框中,选择“Web API”,然后单击“确定”

创建 ASP.net Web API 项目
单击“确定”后,将创建一个默认的 web api 项目。在 controllers 文件夹中,将创建一个名为“ValuesController.cs”的文件。这是添加的默认 Web API 服务文件。您可以修改此文件,也可以添加新的 API 控制器。
在“Global.asax”文件中,还在 RegisterRoutes 函数中添加了一个默认的路由映射(只需在 RegisterRoutes 函数上按 F12 键。它将带您到函数定义)
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
您可以修改此文件以反映您想对应用程序进行的任何配置更改。默认情况下包含一个路由作为示例以供您开始使用。
让我们创建我们自己的“Product API 控制器”,而不是修改现有的“ValuesController.cs”
在创建 Product Api 控制器之前,我们将创建 Product 模型和 Product Manager 类。这些类将用于 Product API 控制器中执行 CRUD(创建、读取、更新和删除)操作。
Product 模型
在解决方案资源管理器中,右键单击“Models”文件夹,然后添加以下名为 Product 的类,如下面的屏幕截图所示。

在 ASP.NET Web API 项目中创建模型类

在 ASP.NET Web API 项目中创建模型类
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
同样,在同一个 Model 文件夹中添加以下接口和类。
public interface IProductManager
{
List<Product> GetAll();
Product Get(int id);
Product Add(Product product);
void Remove(int id);
bool Update(Product product);
}
public class ProductManager: IProductManager
{
List<Product> products = new List<Product>();
private int _autoProductId = 1;
public ProductManager()
{
Add(new Product { Name = "Pen", Type = "Stationary", Description = "Pen from Lexi Company", Price = 10 });
Add(new Product { Name = "Ball", Type = "Sports", Description = "Ball from Hedley", Price = 65 });
Add(new Product { Name = "Battery", Type = "Electronics", Description = "Duracell batteries", Price = 20 });
Add(new Product { Name = "Books", Type = "Stationary", Description = "Academic books", Price = 2000 });
Add(new Product { Name = "Gym Bag", Type = "Sports", Description = "Gym Bag from Reebok", Price = 1500 });
}
public List<Product> GetAll()
{
return products;
}
public Product Get(int id)
{
var product = products.Find(p => p.Id == id);
return product;
}
public Product Add(Product product)
{
if (product == null)
{
throw new ArgumentNullException("product");
}
product.Id = _autoProductId++;
products.Add(product);
return product;
}
public void Remove(int id)
{
products.RemoveAll(p => p.Id == id);
}
public bool Update(Product product)
{
if (product == null)
{
throw new ArgumentNullException("product");
}
int index = products.FindIndex(p => p.Id == product.Id);
if (index == -1)
{
return false;
}
products.RemoveAt(index);
products.Add(product);
return true;
}
}
现在我们已准备好创建我们的 Product Web API 控制器。在添加新的 API 控制器之前,从项目中删除位于“Controllers”文件夹内的名为“ValuesController.cs”的文件。
添加 Web API 控制器
在解决方案资源管理器中,右键单击“Controllers”文件夹。选择“添加”,然后选择“控制器”。

在 ASP.NET Web API 项目中创建控制器类
在“添加控制器”对话框中,将控制器命名为 ProductController。在“模板”下拉列表中,选择“空 API 控制器”,然后单击“添加”。

在 ASP.NET Web API 项目中添加模型类
在“ProductController.cs”类中添加以下代码
public class ProductController : ApiController
{
static readonly IProductManager prodManager = new ProductManager();
//Get All Products
[HttpGet]
public List<Product> GetAllProducts()
{
return prodManager.GetAll();
}
//Get Product by id
[HttpGet]
public Product GetProductById(int id)
{
var product = prodManager.Get(id);
if (product == null)
{
throw new HttpResponseException(HttpStatusCode.OK);
}
return product;
}
//Add Product
[HttpPost]
public Product AddProduct(Product product)
{
product = prodManager.Add(product);
return product;
}
//Update Product
[HttpPut]
public void UpdateProduct(Product product)
{
if (!prodManager.Update(product))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
//Delete Product
[HttpDelete]
public void DeleteProduct(int id)
{
Product product = prodManager.Get(id);
if (product == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
prodManager.Remove(id);
}
关注点
恭喜!在此时,我们已成功创建了我们的 Web API 项目。在下一篇文章中,我们将介绍如何使用此 Web API。
你认为呢?
亲爱的读者,
如果您有任何问题或建议,请随时给我发送电子邮件或在下面发表您的评论。我很乐意听取您的意见。如果您觉得这篇帖子或文章有用,请与您的朋友分享,并帮助他们学习。
学习愉快