目录
背景
在上一篇文章《使用类库和实体框架简化MVC WebAPI ASP.NET中的数据访问》中奠定的基础之上,我们在上一篇文章中探讨了使用类库和实体框架(不依赖于.edmx文件)在ASP.NET MVC WebAPI应用程序中简化数据访问,本文将更深入地探讨。在这里,我们将重点介绍WebAPI方法的实际实现,这些方法利用已建立的数据访问层与检索到的数据进行有效的交互。
设置项目
首先,我们将创建一个包含两个项目的解决方案:
- DataAccessLayer(类库):包含用于数据访问的实体框架DbContext和存储库模式。
- MVC Web API项目:托管API终结点并充当后端。
循序渐进的实现
1. DataAccessLayer项目
在DataAccessLayer项目中,我们定义:
- DatabaseTransections:继承自DbContext并设置数据库连接。它包括一个用于ProductEntity的DbSet和使用OnModelCreating的配置。
- ProductEntity:表示具有ID、ProductName、UnitPrice和Quantity等属性的产品。
- ProductRepository:使用实体框架实现CRUD操作。像AddProduct、GetALLProducts、GetProductByName、GetProductByID和deleteProduct这样的方法,并通过DatabaseTransections与数据库交互。
2. MVC Web API项目
在这里,我们创建:
- ProductController:公开用于管理产品的API端点(GET、POST、PUT、DELETE)的控制器。控制器中的每个方法都与ProductRepository交互以执行CRUD操作。
- API方法:
- GetAllProducts:检索所有产品。
- GetProductByName:检索与给定名称匹配的产品。
- AddProduct:将新产品添加到数据库。
- DeleteProduct:按ID删除产品。
public class ProductController : ApiController
{
[HttpGet]
public IEnumerable<ProductEntity> GetAllProducts()
{
return new ProductRepository(new DatabaseTransections()).GetALLProducts();
}
[HttpGet]
public HttpResponseMessage GetProductByName(string productName)
{
var entities = new ProductRepository(new DatabaseTransections()).GetProductByName(productName);
if (entities != null)
return Request.CreateResponse(HttpStatusCode.OK, entities);
else
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Product with Name " + productName + " not found");
}
[HttpPost]
public HttpResponseMessage AddProduct([FromBody]ProductEntity _entity)
{
try
{
new ProductRepository(new DatabaseTransections()).AddProduct(_entity);
var message = Request.CreateResponse(HttpStatusCode.Created, _entity);
message.Headers.Location = new Uri(Request.RequestUri + _entity.ID.ToString());
return message;
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
[HttpDelete()]
public HttpResponseMessage DeleteProduct(int id)
{
try
{
var _repository = new ProductRepository(new DatabaseTransections());
var _entity = _repository.GetProductByID(id);
if (_entity != null)
{
_repository.deleteProduct(_entity);
return Request.CreateResponse(HttpStatusCode.OK);
}
else
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "The product with ID " + id + " not found");
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.Conflict, ex);
}
}
}
HTML
此HTML代码构建了一个具有两个功能的网页:
- 加载所有产品:单击“加载所有产品”按钮会触发一个操作(可能通过JavaScript)以从API中检索产品数据。
- 按名称加载产品:用户可以输入产品名称,然后单击“按名称加载产品”按钮。这可能会使用输入的名称启动搜索函数,以从API获取匹配的产品。
检索到的产品数据将显示在ID为ulProducts的无序列表(<ul>)元素中。
<div class="row">
<div class="col-md-4">
<div class="col-md-12">
<h2>Load All Products</h2>
<p>Click this button to get all product enlisted in database</p>
<input type="button" id="loadAllProducts" class="btn btn-lg btn-default" value="Load all Products"/>
</div>
<div class="col-md-12">
<h2>Load Product by Name</h2>
<div class="form-group">
<input type="text" id="txtProductName" class="form-control">
<span class="badge rounded-pill"></span>
</div>
<p>Mention name of the product and click on button to load matching products from database</p>
<input type="button" id="loadProductsByName" class="btn btn-lg btn-default" value="Load Products by Name"/>
</div>
</div>
<div class="col-md-8">
<ul id="ulProducts" class="list-group w-50"></ul>
</div>
</div>
使用AJAX使用API
要在前端应用程序(如HTML页面)中使用这些API,请执行以下操作:
- index.html:包含HTML结构和AJAX脚本,用于与API端点交互。
- AJAX 调用:使用jQuery AJAX,我们向API端点 (GET、POST、DELETE)发出异步请求。
<script type="text/javascript">
$(document).ready(function () {
var ulProducts = $("#ulProducts");
$("#loadAllProducts").click(function () {
$(ulProducts).empty();
$.ajax({
type: "GET",
url: "http://localhost:53078/api/Product",
datatype: "json",
success: function (data) {
$.each(data, function (index, val) {
ulProducts.append("<li class=\"list-group-item\"><i class=\"glyphicon glyphicon-trash\" onClick = \"deleteProduct(this," + val.ID + ")\"></i> " + val.ProductName + "<span class=\"badge rounded-pill\">" + val.Quantity + "</span></li>");
});
}
});
});
$("#loadProductsByName").click(function () {
var productName = $("#txtProductName").val();
$(ulProducts).empty();
$.ajax({
type: "GET",
url: "http://localhost:53078/api/Product",
datatype: "json",
data: { productName: productName },
success: function (data) {
$.each(data, function (index, val) {
ulProducts.append("<li class=\"list-group-item\"><i class=\"glyphicon glyphicon-trash\" onClick = \"deleteProduct(this," + val.ID + ")\"></i> " + val.ProductName + "<span class=\"badge rounded-pill\">" + val.Quantity + "</span></li>");
});
}
});
});
});
function deleteProduct(listItem, productID) {
debugger;
$.ajax({
type: "DELETE",
url: "http://localhost:53078/api/Product/" + productID,
datatype: "json",
success: function (data, textStatus, xhr) {
if (xhr.status == 200) // SUCCESS
$(listItem).parent().remove();
}
});
}
</script>
结论
在本文中,我们介绍了如何使用Web API构建RESTful API、实现CRUD操作以及在前端应用程序中使用AJAX ASP.NET API。此设置允许后端和前端之间的无缝交互,从而实现现代Web应用程序开发实践。
通过遵循这些步骤和示例,开发人员可以创建强大的API,并将它们有效地集成到他们的Web应用程序中,从而增强用户体验和开发人员的工作效率。
https://www.codeproject.com/Articles/5384156/Building-a-RESTful-API-with-ASP-NET-Web-API-and-Co