在本文中,将深入探讨如何使用ASP.NETMVCWebAPI和Entity Framework构建RESTful API,并在前端应用中使用AJAX进行调用。这种设置允许后端和前端之间无缝交互,实现现代Web应用开发实践。
首先,将创建一个包含两个项目的解决方案:
在数据访问层项目中,定义:
在这里,创建:
以下是一些API方法的示例:
以下是ProductController的C#代码示例:
public class ProductController : ApiController
{
[HttpGet]
public IEnumerable<ProductEntity> GetAllProducts()
{
return new ProductRepository(new DatabaseTransactions()).GetALLProducts();
}
[HttpGet]
public HttpResponseMessage GetProductByName(string productName)
{
var entities = new ProductRepository(new DatabaseTransactions()).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 DatabaseTransactions()).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 DatabaseTransactions());
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代码结构了一个网页,具有以下功能:
检索到的产品数据将在ID为ulProducts的无序列表(
点击此按钮以获取数据库中列出的所有产品。
输入产品名称并点击按钮以从数据库加载匹配的产品。