65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 ASP.NET Web API 构建 RESTful API 并使用 AJAX 消费

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.95/5 (4投票s)

2024年6月25日

CPOL

2分钟阅读

viewsIcon

6503

使用 ASP.NET Web API 构建 RESTful API,并使用 AJAX 消费它,以便在前端和后端之间实现无缝交互。

背景

基于我们之前的文章, 使用类库和实体框架简化 ASP.NET MVC WebAPI 中的数据访问,我们在其中探讨了使用类库和实体框架 (无需依赖 .edmx 文件) 在 ASP.NET MVC WebAPI 应用程序中简化数据访问的方法,本文将深入探讨。在这里,我们将重点关注利用已建立的数据访问层来有效与检索到的数据交互的 WebAPI 方法的实际实现。

设置项目

首先,我们将创建一个包含两个项目的解决方案

  1. DataAccessLayer(类库):包含实体框架 DbContext 和用于数据访问的存储库模式。
  2. MVC Web API 项目:托管 API 终结点并充当后端。

分步实施

1. DataAccessLayer 项目

在 DataAccessLayer 项目中,我们定义

  • DatabaseTransections:继承自 DbContext 并设置数据库连接。它包括一个 DbSet 用于 ProductEntity 以及使用 OnModelCreating 进行的配置。

  • ProductEntity:表示一个产品,具有 ID、ProductName、UnitPrice 和 Quantity 等属性。

  • ProductRepository:使用实体框架实现 CRUD 操作。AddProductGetALLProductsGetProductByNameGetProductByIDdeleteProduct 等方法通过 DatabaseTransections 与数据库交互。

2. MVC Web API 项目

在这里,我们创建

  • ProductController:一个控制器,公开 API 终结点 (GETPOSTPUTDELETE) 用于管理产品。控制器中的每个方法都与 ProductRepository 交互以执行 CRUD 操作。

  • API 方法:

  1. GetAllProducts:检索所有产品。
  2. GetProductByName:检索与给定名称匹配的产品。
  3. AddProduct:向数据库添加新产品。
  4. 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 代码构建了一个具有两个功能的网页

  1. 加载所有产品: 单击“加载所有产品”按钮会触发一个操作(可能通过 JavaScript)以从 API 检索产品数据。
  2. 按名称加载产品: 用户可以输入产品名称并单击“按名称加载产品”按钮。这可能会启动一个搜索功能,使用输入的名称从 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 终结点 (GETPOSTDELETE) 发出异步请求。

<script type="text/javascript">

    $(document).ready(function () {
        var ulProducts = $("#ulProducts");
        $("#loadAllProducts").click(function () {
            $(ulProducts).empty();
            $.ajax({
                type: "GET",
                url: "https://: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: "https://: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: "https://:53078/api/Product/" + productID,
            datatype: "json",
            success: function (data, textStatus, xhr) {
                if (xhr.status == 200) // SUCCESS
                    $(listItem).parent().remove();
            }
            
        });
    }

</script>

结论

在本文中,我们介绍了如何使用 ASP.NET Web API 构建 RESTful API,实现 CRUD 操作,以及如何在前端应用程序中使用 AJAX 消费 API。此设置允许后端和前端之间无缝交互,从而实现现代 Web 应用程序开发实践。

通过遵循这些步骤和示例,开发人员可以创建强大的 API 并将其有效地集成到其 Web 应用程序中,从而提高用户体验和开发人员生产力。

© . All rights reserved.