在本文中,我们将探讨如何使用最新实践(包括依赖项注入)创建健壮的 ASP.NET Core Web API,以及使用控制器、服务层和存储库层构建应用程序。我们还将集成 Gridify NuGet 包,以演示跨多个使用案例的高级筛选功能,所有这些都在同一路由中。
创建新的 ASP.NET Core Web API 项目:
dotnet new webapi -n GridifyAdvancedDemo
cd GridifyAdvancedDemo
**安装所需的 NuGet 包:**Add 和任何其他必要的包。Gridify
dotnet add package Gridify
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.InMemory
定义您的模型:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
设置存储库层:
public interface IProductRepository
{
IQueryable<Product> GetProducts();
}
public class ProductRepository : IProductRepository
{
private readonly List<Product> _products;
public ProductRepository()
{
// Sample data
_products = new List<Product>
{
new Product { Id = 1, Name = "Product A", Price = 10.99m, Category = "Category1" },
new Product { Id = 2, Name = "Product B", Price = 20.99m, Category = "Category2" },
// Add more products
};
}
public IQueryable<Product> GetProducts()
{
return _products.AsQueryable();
}
}
创建服务层:
public interface IProductService
{
IQueryable<Product> GetFilteredProducts(GridifyQuery gridifyQuery);
}
public class ProductService : IProductService
{
private readonly IProductRepository _productRepository;
public ProductService(IProductRepository productRepository)
{
_productRepository = productRepository;
}
public IQueryable<Product> GetFilteredProducts(GridifyQuery gridifyQuery)
{
var products = _productRepository.GetProducts().Gridify(gridifyQuery);
return products;
}
}
设置控制器:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly IProductService _productService;
public ProductsController(IProductService productService)
{
_productService = productService;
}
[HttpGet]
public IActionResult GetProducts([FromQuery] GridifyQuery gridifyQuery)
{
var products = _productService.GetFilteredProducts(gridifyQuery);
return Ok(products);
}
}
在 中配置依赖关系注入 :Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
现在,让我们探索五个不同的使用案例,在这些案例中,我们使用相同的路由和不同的 Gridify 过滤器。GET /api/products
请求:
GET /api/products?filter=Category==Category1
此请求筛选 为 “Category1” 的产品。Category
请求:
GET /api/products?filter=Price>15&sort=Price
此查询筛选价格大于 15 的产品,并按升序对它们进行排序。Price
请求:
GET /api/products?page=1&pageSize=2
此请求对结果进行分页,显示前两个产品。
请求:
GET /api/products?filter=Category==Category2&sort=Name&page=2&pageSize=1
此示例按 筛选产品,按 对产品进行排序,并返回第二个页面,每页一个产品。Category2Name
请求:
GET /api/products?filter=(Category==Category1||Price>50)&&Name@=*B
此查询返回属于“Category1”或价格大于 50 且其名称包含字母“B”的产品。
上面演示的使用案例展示了如何最大限度地发挥 Gridify 的强大功能,同时通过适当的分层和依赖项注入来保持代码的干净和可维护。