185 lines
8.1 KiB
C#
185 lines
8.1 KiB
C#
using System.IO.Compression;
|
|
using System.Text.Json.Serialization;
|
|
|
|
namespace MinimalAPI
|
|
{
|
|
// 定义数据模型
|
|
record Category(int Id, string Name, string Description);
|
|
record Product(int Id, string Name, string Model, string Manufacturer, int CategoryId, int CurrentRank, DateTime ReleaseDate, decimal? Price);
|
|
record ApiResponse<T>(bool Success, T? Data, string? Message = null);
|
|
record PagedResponse<T>(List<T> Items, int TotalCount, int PageNumber, int PageSize, int TotalPages);
|
|
record ComparisonRequest(List<int> ProductIds);
|
|
|
|
public class Program
|
|
{
|
|
public static void Main(string[] args)
|
|
{
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
// 配置响应压缩
|
|
builder.Services.AddResponseCompression(options =>
|
|
{
|
|
options.EnableForHttps = true;
|
|
options.Providers.Add<BrotliCompressionProvider>();
|
|
options.Providers.Add<GzipCompressionProvider>();
|
|
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
|
|
{
|
|
"application/json",
|
|
"application/javascript",
|
|
"text/css",
|
|
"text/html",
|
|
"text/plain",
|
|
"text/xml"
|
|
});
|
|
});
|
|
|
|
builder.Services.Configure<BrotliCompressionProviderOptions>(options =>
|
|
{
|
|
options.Level = CompressionLevel.Fastest;
|
|
});
|
|
|
|
builder.Services.Configure<GzipCompressionProviderOptions>(options =>
|
|
{
|
|
options.Level = CompressionLevel.Fastest;
|
|
});
|
|
|
|
// 配置JSON序列化选项
|
|
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
|
|
{
|
|
options.SerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
|
|
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
|
|
});
|
|
|
|
// 配置CORS
|
|
builder.Services.AddCors(options =>
|
|
{
|
|
options.AddPolicy("AllowAll", policy =>
|
|
{
|
|
policy.AllowAnyOrigin()
|
|
.AllowAnyMethod()
|
|
.AllowAnyHeader();
|
|
});
|
|
});
|
|
|
|
// 注册服务
|
|
builder.Services.AddScoped<ICategoryService, CategoryService>();
|
|
builder.Services.AddScoped<IProductService, ProductService>();
|
|
builder.Services.AddScoped<IComparisonService, ComparisonService>();
|
|
|
|
var app = builder.Build();
|
|
|
|
// 添加响应压缩中间件
|
|
app.UseResponseCompression();
|
|
|
|
// 使用CORS
|
|
app.UseCors("AllowAll");
|
|
|
|
// 模拟数据
|
|
var categories = new List<Category>
|
|
{
|
|
new(1, "手机CPU", "移动设备处理器"),
|
|
new(2, "手机GPU", "移动设备图形处理器"),
|
|
new(3, "电脑CPU", "桌面和笔记本处理器"),
|
|
new(4, "电脑GPU", "桌面和笔记本图形处理器")
|
|
};
|
|
|
|
var products = new List<Product>
|
|
{
|
|
new(1, "Apple A17 Pro", "A17 Pro", "Apple", 1, 1, new DateTime(2023, 9, 12), null),
|
|
new(2, "Snapdragon 8 Gen 3", "SM8650-AB", "Qualcomm", 1, 2, new DateTime(2023, 10, 24), null),
|
|
new(3, "Intel Core i9-13900K", "Core i9-13900K", "Intel", 3, 1, new DateTime(2022, 10, 20), 589.99m),
|
|
new(4, "AMD Ryzen 9 7950X", "Ryzen 9 7950X", "AMD", 3, 2, new DateTime(2022, 9, 27), 699.99m),
|
|
new(5, "NVIDIA GeForce RTX 4090", "RTX 4090", "NVIDIA", 4, 1, new DateTime(2022, 10, 12), 1599.99m),
|
|
new(6, "AMD Radeon RX 7900 XTX", "RX 7900 XTX", "AMD", 4, 2, new DateTime(2022, 12, 3), 999.99m)
|
|
};
|
|
|
|
// API端点
|
|
|
|
// 类别相关
|
|
app.MapGet("/api/categories", async (ICategoryService categoryService) =>
|
|
{
|
|
var categories = await categoryService.GetAllCategoriesAsync();
|
|
return Results.Ok(new ApiResponse<List<CategoryDto>>(true, categories));
|
|
});
|
|
|
|
app.MapGet("/api/categories/{id}", async (int id, ICategoryService categoryService) =>
|
|
{
|
|
var category = await categoryService.GetCategoryByIdAsync(id);
|
|
if (category == null)
|
|
{
|
|
return Results.NotFound(new ApiResponse<object>(false, null, "类别不存在"));
|
|
}
|
|
return Results.Ok(new ApiResponse<CategoryDto>(true, category));
|
|
});
|
|
|
|
// 产品API
|
|
app.MapGet("/api/products", async (int? categoryId, int page = 1, int pageSize = 20, string sortBy = "CurrentRank", string sortOrder = "asc", IProductService productService) =>
|
|
{
|
|
if (!categoryId.HasValue)
|
|
{
|
|
return Results.BadRequest(new ApiResponse<object>(false, null, "类别ID是必需的"));
|
|
}
|
|
|
|
var pagedResult = await productService.GetProductsByCategoryAsync(categoryId.Value, page, pageSize, sortBy, sortOrder);
|
|
return Results.Ok(new ApiResponse<PagedResultDto<ProductListDto>>(true, pagedResult));
|
|
});
|
|
|
|
app.MapGet("/api/products/{id}", async (int id, IProductService productService) =>
|
|
{
|
|
var product = await productService.GetProductByIdAsync(id);
|
|
if (product == null)
|
|
{
|
|
return Results.NotFound(new ApiResponse<object>(false, null, "产品不存在"));
|
|
}
|
|
return Results.Ok(new ApiResponse<ProductDto>(true, product));
|
|
});
|
|
|
|
app.MapGet("/api/products/search", async (string q, int? categoryId, string? manufacturer, decimal? minScore, decimal? maxScore, int page = 1, int pageSize = 20, IProductService productService) =>
|
|
{
|
|
if (string.IsNullOrWhiteSpace(q))
|
|
{
|
|
return Results.BadRequest(new ApiResponse<object>(false, null, "搜索关键词不能为空"));
|
|
}
|
|
|
|
var pagedResult = await productService.SearchProductsAsync(q, categoryId, manufacturer, minScore, maxScore, page, pageSize);
|
|
return Results.Ok(new ApiResponse<PagedResultDto<ProductListDto>>(true, pagedResult));
|
|
});
|
|
|
|
app.MapGet("/api/products/filter", async (int categoryId, string? manufacturer, decimal? minScore, decimal? maxScore, int? year, int page = 1, int pageSize = 20, IProductService productService) =>
|
|
{
|
|
var pagedResult = await productService.FilterProductsAsync(categoryId, manufacturer, minScore, maxScore, year, page, pageSize);
|
|
return Results.Ok(new ApiResponse<PagedResultDto<ProductListDto>>(true, pagedResult));
|
|
});
|
|
|
|
// 产品对比
|
|
app.MapPost("/api/comparison", async (ComparisonRequest request, IComparisonService comparisonService) =>
|
|
{
|
|
// 验证请求
|
|
if (request.ProductIds == null || request.ProductIds.Count < 2 || request.ProductIds.Count > 4)
|
|
{
|
|
return Results.BadRequest(new ApiResponse<object>(false, null, "产品ID数量必须在2到4之间"));
|
|
}
|
|
|
|
var comparisonData = await comparisonService.CompareProductsAsync(request.ProductIds);
|
|
if (comparisonData == null)
|
|
{
|
|
return Results.NotFound(new ApiResponse<object>(false, null, "无法获取产品对比数据"));
|
|
}
|
|
|
|
return Results.Ok(new ApiResponse<object>(true, comparisonData));
|
|
});
|
|
|
|
// 状态检查端点
|
|
app.MapGet("/api/status", () => new
|
|
{
|
|
Status = "Running",
|
|
Message = "API服务正常运行",
|
|
Timestamp = DateTime.Now,
|
|
Version = "1.0.0"
|
|
});
|
|
|
|
app.Run();
|
|
}
|
|
}
|
|
}
|