using System.Text.Json.Serialization; using OptixServe.Core.Services; using OptixServe.Api.Dtos; namespace OptixServe.Api.Endpoints; [JsonSerializable(typeof(UserDto))] [JsonSerializable(typeof(IEnumerable))] public partial class UserJsonContext : JsonSerializerContext { } public class UserEndpoint { private readonly IUserService _userService; // 通过构造函数注入依赖 public UserEndpoint(IUserService userService) { _userService = userService; } public static void Register(WebApplication app) { var group = app.MapGroup("/users"); group.MapGet("/", (UserEndpoint endpoint) => endpoint.GetAllUsers()); group.MapGet("/{id}", (string id, UserEndpoint endpoint) => endpoint.GetUserById(id)); } public IResult GetAllUsers() { var users = _userService.GetUsers() .Select(u => new UserDto { Id = u.Id, UserName = u.UserName }); return Results.Ok(users); } public IResult GetUserById(string id) { var user = _userService.GetUserById(id); if (user == null) return Results.NotFound(); return Results.Ok(new UserDto { Id = user.Id, UserName = user.UserName }); } }