This commit is contained in:
2025-11-03 17:03:57 +08:00
commit 7a04b85667
16804 changed files with 2492292 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
using Microsoft.AspNetCore.Mvc;
using HardwarePerformance.API.Models;
namespace HardwarePerformance.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CategoriesController : ControllerBase
{
private static readonly List<Category> _categories = new()
{
new Category { Id = 1, Name = "手机CPU", Description = "移动设备处理器" },
new Category { Id = 2, Name = "手机GPU", Description = "移动设备图形处理器" },
new Category { Id = 3, Name = "电脑CPU", Description = "桌面和笔记本处理器" },
new Category { Id = 4, Name = "电脑GPU", Description = "桌面和笔记本图形处理器" }
};
[HttpGet]
public ApiResponse<IEnumerable<Category>> GetCategories()
{
return new ApiResponse<IEnumerable<Category>>
{
Data = _categories
};
}
[HttpGet("{id}")]
public ActionResult<ApiResponse<Category>> GetCategory(int id)
{
var category = _categories.FirstOrDefault(c => c.Id == id);
if (category == null)
{
return NotFound(new ApiResponse<Category>
{
Success = false,
Message = "未找到指定的类别"
});
}
return Ok(new ApiResponse<Category>
{
Data = category
});
}
}
}

View File

@@ -0,0 +1,313 @@
using Microsoft.AspNetCore.Mvc;
using HardwarePerformance.API.Models;
namespace HardwarePerformance.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ComparisonController : ControllerBase
{
private static readonly List<Product> _products = new()
{
new Product
{
Id = 1,
Name = "Apple A17 Pro",
Model = "A17 Pro",
Manufacturer = "Apple",
CategoryId = 1,
CurrentRank = 1,
ReleaseDate = new DateTime(2023, 9, 12),
Price = null
},
new Product
{
Id = 2,
Name = "Snapdragon 8 Gen 3",
Model = "SM8650-AB",
Manufacturer = "Qualcomm",
CategoryId = 1,
CurrentRank = 2,
ReleaseDate = new DateTime(2023, 10, 24),
Price = null
},
new Product
{
Id = 3,
Name = "Intel Core i9-13900K",
Model = "Core i9-13900K",
Manufacturer = "Intel",
CategoryId = 3,
CurrentRank = 1,
ReleaseDate = new DateTime(2022, 10, 20),
Price = 589.99m
},
new Product
{
Id = 4,
Name = "AMD Ryzen 9 7950X",
Model = "Ryzen 9 7950X",
Manufacturer = "AMD",
CategoryId = 3,
CurrentRank = 2,
ReleaseDate = new DateTime(2022, 9, 27),
Price = 699.99m
},
new Product
{
Id = 5,
Name = "NVIDIA GeForce RTX 4090",
Model = "RTX 4090",
Manufacturer = "NVIDIA",
CategoryId = 4,
CurrentRank = 1,
ReleaseDate = new DateTime(2022, 10, 12),
Price = 1599.99m
},
new Product
{
Id = 6,
Name = "AMD Radeon RX 7900 XTX",
Model = "RX 7900 XTX",
Manufacturer = "AMD",
CategoryId = 4,
CurrentRank = 2,
ReleaseDate = new DateTime(2022, 12, 3),
Price = 999.99m
}
};
[HttpPost]
public ActionResult<ApiResponse<object>> CompareProducts([FromBody] ComparisonRequest request)
{
// 验证请求
if (request.ProductIds == null || request.ProductIds.Count < 2 || request.ProductIds.Count > 4)
{
return BadRequest(new ApiResponse<object>
{
Success = false,
Message = "产品ID数量必须在2到4之间"
});
}
// 获取产品
var products = _products.Where(p => request.ProductIds.Contains(p.Id)).ToList();
if (products.Count != request.ProductIds.Count)
{
return NotFound(new ApiResponse<object>
{
Success = false,
Message = "一个或多个产品ID无效"
});
}
// 检查是否所有产品属于同一类别
var categories = products.Select(p => p.CategoryId).Distinct().ToList();
if (categories.Count > 1)
{
return BadRequest(new ApiResponse<object>
{
Success = false,
Message = "所有产品必须属于同一类别"
});
}
// 创建对比数据
var comparisonData = new
{
Products = products.Select(p => new
{
p.Id,
p.Name,
p.Model,
p.Manufacturer,
p.CategoryId,
p.CurrentRank,
p.ReleaseDate,
p.Price,
PerformanceScore = 100 - p.CurrentRank // 使用排名计算模拟性能分数
}).ToList(),
Comparison = GenerateComparisonMatrix(products)
};
return Ok(new ApiResponse<object>
{
Data = comparisonData
});
}
private object GenerateComparisonMatrix(List<Product> products)
{
var matrix = new List<Dictionary<string, object>>();
// 添加基本信息行
matrix.Add(new Dictionary<string, object>
{
["指标"] = "产品名称",
["类型"] = "基本信息"
});
foreach (var product in products)
{
matrix[0][$"{product.Name}"] = product.Name;
}
// 添加制造商行
matrix.Add(new Dictionary<string, object>
{
["指标"] = "制造商",
["类型"] = "基本信息"
});
foreach (var product in products)
{
matrix[1][$"{product.Name}"] = product.Manufacturer;
}
// 添加型号行
matrix.Add(new Dictionary<string, object>
{
["指标"] = "型号",
["类型"] = "基本信息"
});
foreach (var product in products)
{
matrix[2][$"{product.Name}"] = product.Model;
}
// 添加排名行
matrix.Add(new Dictionary<string, object>
{
["指标"] = "当前排名",
["类型"] = "性能指标"
});
foreach (var product in products)
{
matrix[3][$"{product.Name}"] = product.CurrentRank;
}
// 添加性能分数行(模拟)
matrix.Add(new Dictionary<string, object>
{
["指标"] = "性能分数",
["类型"] = "性能指标"
});
foreach (var product in products)
{
matrix[4][$"{product.Name}"] = 100 - product.CurrentRank;
}
// 添加发布日期行
matrix.Add(new Dictionary<string, object>
{
["指标"] = "发布日期",
["类型"] = "基本信息"
});
foreach (var product in products)
{
matrix[5][$"{product.Name}"] = product.ReleaseDate.ToString("yyyy-MM-dd");
}
// 添加价格行
matrix.Add(new Dictionary<string, object>
{
["指标"] = "价格",
["类型"] = "基本信息"
});
foreach (var product in products)
{
matrix[6][$"{product.Name}"] = product.Price?.ToString("C") ?? "N/A";
}
// 标记最优和最差值
MarkBestAndWorstValues(matrix, products);
return matrix;
}
private void MarkBestAndWorstValues(List<Dictionary<string, object>> matrix, List<Product> products)
{
// 对于排名,越小越好
var rankRow = matrix.FirstOrDefault(m => m["指标"].ToString() == "当前排名");
if (rankRow != null)
{
var ranks = products.Select(p => p.CurrentRank).ToList();
var minRank = ranks.Min();
var maxRank = ranks.Max();
foreach (var product in products)
{
var rank = product.CurrentRank;
if (rank == minRank)
{
rankRow[$"{product.Name}_isBest"] = true;
}
else if (rank == maxRank)
{
rankRow[$"{product.Name}_isWorst"] = true;
}
}
}
// 对于性能分数,越大越好
var scoreRow = matrix.FirstOrDefault(m => m["指标"].ToString() == "性能分数");
if (scoreRow != null)
{
var scores = products.Select(p => 100 - p.CurrentRank).ToList();
var maxScore = scores.Max();
var minScore = scores.Min();
foreach (var product in products)
{
var score = 100 - product.CurrentRank;
if (score == maxScore)
{
scoreRow[$"{product.Name}_isBest"] = true;
}
else if (score == minScore)
{
scoreRow[$"{product.Name}_isWorst"] = true;
}
}
}
// 对于价格,越小越好
var priceRow = matrix.FirstOrDefault(m => m["指标"].ToString() == "价格");
if (priceRow != null)
{
var prices = products.Where(p => p.Price.HasValue).Select(p => p.Price!.Value).ToList();
if (prices.Any())
{
var minPrice = prices.Min();
var maxPrice = prices.Max();
foreach (var product in products)
{
if (product.Price.HasValue)
{
if (product.Price == minPrice)
{
priceRow[$"{product.Name}_isBest"] = true;
}
else if (product.Price == maxPrice)
{
priceRow[$"{product.Name}_isWorst"] = true;
}
}
}
}
}
}
}
public class ComparisonRequest
{
public List<int> ProductIds { get; set; } = new();
}
}

View File

@@ -0,0 +1,252 @@
using Microsoft.AspNetCore.Mvc;
using HardwarePerformance.API.Models;
using HardwarePerformance.Infrastructure.Services;
namespace HardwarePerformance.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static readonly List<Product> _products = new()
{
new Product
{
Id = 1,
Name = "Apple A17 Pro",
Model = "A17 Pro",
Manufacturer = "Apple",
CategoryId = 1,
CurrentRank = 1,
ReleaseDate = new DateTime(2023, 9, 12),
Price = null
},
new Product
{
Id = 2,
Name = "Snapdragon 8 Gen 3",
Model = "SM8650-AB",
Manufacturer = "Qualcomm",
CategoryId = 1,
CurrentRank = 2,
ReleaseDate = new DateTime(2023, 10, 24),
Price = null
},
new Product
{
Id = 3,
Name = "Intel Core i9-13900K",
Model = "Core i9-13900K",
Manufacturer = "Intel",
CategoryId = 3,
CurrentRank = 1,
ReleaseDate = new DateTime(2022, 10, 20),
Price = 589.99m
},
new Product
{
Id = 4,
Name = "AMD Ryzen 9 7950X",
Model = "Ryzen 9 7950X",
Manufacturer = "AMD",
CategoryId = 3,
CurrentRank = 2,
ReleaseDate = new DateTime(2022, 9, 27),
Price = 699.99m
},
new Product
{
Id = 5,
Name = "NVIDIA GeForce RTX 4090",
Model = "RTX 4090",
Manufacturer = "NVIDIA",
CategoryId = 4,
CurrentRank = 1,
ReleaseDate = new DateTime(2022, 10, 12),
Price = 1599.99m
},
new Product
{
Id = 6,
Name = "AMD Radeon RX 7900 XTX",
Model = "RX 7900 XTX",
Manufacturer = "AMD",
CategoryId = 4,
CurrentRank = 2,
ReleaseDate = new DateTime(2022, 12, 3),
Price = 999.99m
}
};
private readonly IRedisCacheService _cacheService;
public ProductsController(IRedisCacheService cacheService)
{
_cacheService = cacheService;
}
[HttpGet]
public async Task<ActionResult<PagedResponse<Product>>> GetProducts(
[FromQuery] int? categoryId,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 10,
[FromQuery] string sortBy = "CurrentRank",
[FromQuery] string order = "asc")
{
// 创建缓存键
var cacheKey = $"products:list:{categoryId ?? 0}:{page}:{pageSize}:{sortBy}:{order}";
// 尝试从缓存获取数据
var cachedResult = await _cacheService.GetAsync<PagedResponse<Product>>(cacheKey);
if (cachedResult != null)
{
return Ok(cachedResult);
}
var query = _products.AsEnumerable();
if (categoryId.HasValue)
{
query = query.Where(p => p.CategoryId == categoryId.Value);
}
// 排序
query = sortBy.ToLower() switch
{
"name" => order.ToLower() == "desc" ? query.OrderByDescending(p => p.Name) : query.OrderBy(p => p.Name),
"manufacturer" => order.ToLower() == "desc" ? query.OrderByDescending(p => p.Manufacturer) : query.OrderBy(p => p.Manufacturer),
"releasedate" => order.ToLower() == "desc" ? query.OrderByDescending(p => p.ReleaseDate) : query.OrderBy(p => p.ReleaseDate),
"price" => order.ToLower() == "desc" ? query.OrderByDescending(p => p.Price) : query.OrderBy(p => p.Price),
_ => order.ToLower() == "desc" ? query.OrderByDescending(p => p.CurrentRank) : query.OrderBy(p => p.CurrentRank)
};
var totalCount = query.Count();
var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
var items = query.Skip((page - 1) * pageSize).Take(pageSize).ToList();
var result = new PagedResponse<Product>
{
Items = items,
TotalCount = totalCount,
PageNumber = page,
PageSize = pageSize,
TotalPages = totalPages
};
// 将结果存入缓存设置5分钟过期时间
await _cacheService.SetAsync(cacheKey, result, TimeSpan.FromMinutes(5));
return Ok(result);
}
[HttpGet("{id}")]
public async Task<ActionResult<ApiResponse<Product>>> GetProduct(int id)
{
// 创建缓存键
var cacheKey = $"product:detail:{id}";
// 尝试从缓存获取数据
var cachedResult = await _cacheService.GetAsync<ApiResponse<Product>>(cacheKey);
if (cachedResult != null)
{
return Ok(cachedResult);
}
var product = _products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
var notFoundResponse = new ApiResponse<Product>
{
Success = false,
Message = "未找到指定的产品"
};
// 缓存未找到的结果,设置较短过期时间
await _cacheService.SetAsync(cacheKey, notFoundResponse, TimeSpan.FromMinutes(1));
return NotFound(notFoundResponse);
}
var result = new ApiResponse<Product>
{
Data = product
};
// 将结果存入缓存设置15分钟过期时间
await _cacheService.SetAsync(cacheKey, result, TimeSpan.FromMinutes(15));
return Ok(result);
}
[HttpGet("search")]
public async Task<ActionResult<PagedResponse<Product>>> SearchProducts(
[FromQuery] string q,
[FromQuery] int? categoryId,
[FromQuery] string? manufacturer,
[FromQuery] int? minScore,
[FromQuery] int? maxScore,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 10)
{
// 创建缓存键
var cacheKey = $"products:search:{q ?? ""}:{categoryId ?? 0}:{manufacturer ?? ""}:{minScore ?? 0}:{maxScore ?? 0}:{page}:{pageSize}";
// 尝试从缓存获取数据
var cachedResult = await _cacheService.GetAsync<PagedResponse<Product>>(cacheKey);
if (cachedResult != null)
{
return Ok(cachedResult);
}
var query = _products.AsEnumerable();
if (!string.IsNullOrWhiteSpace(q))
{
query = query.Where(p =>
p.Name.Contains(q, StringComparison.OrdinalIgnoreCase) ||
p.Model.Contains(q, StringComparison.OrdinalIgnoreCase) ||
p.Manufacturer.Contains(q, StringComparison.OrdinalIgnoreCase));
}
if (categoryId.HasValue)
{
query = query.Where(p => p.CategoryId == categoryId.Value);
}
if (!string.IsNullOrWhiteSpace(manufacturer))
{
query = query.Where(p =>
p.Manufacturer.Equals(manufacturer, StringComparison.OrdinalIgnoreCase));
}
// 注意这里我们使用CurrentRank作为性能分数的替代因为实际产品中没有性能分数字段
if (minScore.HasValue)
{
query = query.Where(p => (100 - p.CurrentRank) >= minScore.Value);
}
if (maxScore.HasValue)
{
query = query.Where(p => (100 - p.CurrentRank) <= maxScore.Value);
}
var totalCount = query.Count();
var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
var items = query.Skip((page - 1) * pageSize).Take(pageSize).ToList();
var result = new PagedResponse<Product>
{
Items = items,
TotalCount = totalCount,
PageNumber = page,
PageSize = pageSize,
TotalPages = totalPages
};
// 将结果存入缓存设置3分钟过期时间搜索结果变化较快
await _cacheService.SetAsync(cacheKey, result, TimeSpan.FromMinutes(3));
return Ok(result);
}
}
}

View File

@@ -0,0 +1,57 @@
using Microsoft.AspNetCore.Mvc;
namespace HardwarePerformance.API.Controllers;
[ApiController]
[Route("api/[controller]")]
public class SimpleTestController : ControllerBase
{
private readonly ILogger<SimpleTestController> _logger;
public SimpleTestController(ILogger<SimpleTestController> logger)
{
_logger = logger;
}
[HttpGet("status")]
public IActionResult GetStatus()
{
return Ok(new
{
Status = "Running",
Message = "API服务正常运行",
Timestamp = DateTime.Now,
Version = "1.0.0"
});
}
[HttpGet("test-data")]
public IActionResult GetTestData()
{
var categories = new[]
{
new { Id = 1, Name = "手机CPU", Description = "移动设备处理器" },
new { Id = 2, Name = "手机GPU", Description = "移动设备图形处理器" },
new { Id = 3, Name = "电脑CPU", Description = "桌面和笔记本处理器" },
new { Id = 4, Name = "电脑GPU", Description = "桌面和笔记本图形处理器" }
};
var products = new[]
{
new { Id = 1, Name = "Apple A17 Pro", Model = "A17 Pro", Manufacturer = "Apple", CategoryId = 1, CurrentRank = 1 },
new { Id = 2, Name = "Snapdragon 8 Gen 3", Model = "SM8650-AB", Manufacturer = "Qualcomm", CategoryId = 1, CurrentRank = 2 },
new { Id = 3, Name = "Intel Core i9-13900K", Model = "Core i9-13900K", Manufacturer = "Intel", CategoryId = 3, CurrentRank = 1 },
new { Id = 4, Name = "AMD Ryzen 9 7950X", Model = "Ryzen 9 7950X", Manufacturer = "AMD", CategoryId = 3, CurrentRank = 2 },
new { Id = 5, Name = "NVIDIA GeForce RTX 4090", Model = "RTX 4090", Manufacturer = "NVIDIA", CategoryId = 4, CurrentRank = 1 },
new { Id = 6, Name = "AMD Radeon RX 7900 XTX", Model = "RX 7900 XTX", Manufacturer = "AMD", CategoryId = 4, CurrentRank = 2 }
};
return Ok(new
{
Categories = categories,
Products = products,
TotalCategories = categories.Length,
TotalProducts = products.Length
});
}
}

View File

@@ -0,0 +1,154 @@
using Microsoft.AspNetCore.Mvc;
using HardwarePerformance.Infrastructure.Data;
namespace HardwarePerformance.API.Controllers;
[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
private readonly SimpleAppDbContext _context;
private readonly ILogger<TestController> _logger;
public TestController(SimpleAppDbContext context, ILogger<TestController> logger)
{
_context = context;
_logger = logger;
}
[HttpGet("database-status")]
public async Task<IActionResult> GetDatabaseStatus()
{
try
{
var isConnected = await _context.TestConnectionAsync();
return Ok(new
{
IsConnected = isConnected,
Message = isConnected ? "数据库连接成功" : "数据库连接失败",
Timestamp = DateTime.Now
});
}
catch (Exception ex)
{
_logger.LogError(ex, "检查数据库连接时发生错误");
return StatusCode(500, new
{
IsConnected = false,
Message = $"检查数据库连接时发生错误: {ex.Message}",
Timestamp = DateTime.Now
});
}
}
[HttpPost("initialize-database")]
public async Task<IActionResult> InitializeDatabase()
{
try
{
await _context.InitializeDatabaseAsync();
await _context.SeedInitialDataAsync();
return Ok(new
{
Message = "数据库初始化成功,种子数据已添加",
Timestamp = DateTime.Now
});
}
catch (Exception ex)
{
_logger.LogError(ex, "初始化数据库时发生错误");
return StatusCode(500, new
{
Message = $"初始化数据库时发生错误: {ex.Message}",
Timestamp = DateTime.Now
});
}
}
[HttpGet("categories")]
public async Task<IActionResult> GetCategories()
{
try
{
var categories = new List<object>();
using var connection = new MySql.Data.MySqlClient.MySqlConnection(
"Server=localhost;Database=HardwarePerformance;User=root;Password=123456;");
await connection.OpenAsync();
using var cmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM Categories", connection);
using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
categories.Add(new
{
Id = reader.GetInt32("Id"),
Name = reader.GetString("Name"),
Description = reader.IsDBNull("Description") ? null : reader.GetString("Description"),
CreatedAt = reader.GetDateTime("CreatedAt")
});
}
return Ok(categories);
}
catch (Exception ex)
{
_logger.LogError(ex, "获取类别列表时发生错误");
return StatusCode(500, new
{
Message = $"获取类别列表时发生错误: {ex.Message}",
Timestamp = DateTime.Now
});
}
}
[HttpGet("products")]
public async Task<IActionResult> GetProducts()
{
try
{
var products = new List<object>();
using var connection = new MySql.Data.MySqlClient.MySqlConnection(
"Server=localhost;Database=HardwarePerformance;User=root;Password=123456;");
await connection.OpenAsync();
using var cmd = new MySql.Data.MySqlClient.MySqlCommand(
@"SELECT p.*, c.Name as CategoryName
FROM Products p
LEFT JOIN Categories c ON p.CategoryId = c.Id", connection);
using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
products.Add(new
{
Id = reader.GetInt32("Id"),
Name = reader.GetString("Name"),
Model = reader.IsDBNull("Model") ? null : reader.GetString("Model"),
Manufacturer = reader.IsDBNull("Manufacturer") ? null : reader.GetString("Manufacturer"),
ImageUrl = reader.IsDBNull("ImageUrl") ? null : reader.GetString("ImageUrl"),
ReleaseDate = reader.IsDBNull("ReleaseDate") ? (DateTime?)null : reader.GetDateTime("ReleaseDate"),
CategoryId = reader.IsDBNull("CategoryId") ? (int?)null : reader.GetInt32("CategoryId"),
CategoryName = reader.IsDBNull("CategoryName") ? null : reader.GetString("CategoryName"),
CurrentRank = reader.IsDBNull("CurrentRank") ? (int?)null : reader.GetInt32("CurrentRank"),
CreatedAt = reader.GetDateTime("CreatedAt")
});
}
return Ok(products);
}
catch (Exception ex)
{
_logger.LogError(ex, "获取产品列表时发生错误");
return StatusCode(500, new
{
Message = $"获取产品列表时发生错误: {ex.Message}",
Timestamp = DateTime.Now
});
}
}
}