**Note: This implementation is not in minimalAPI way and not optimized, expected to be changed soon.** Add: `UserService` and its interface `IUserService`. Fix: `UserEndpoint` is now in instance class style with DI to work. Fix: change main program to work with above design.
45 lines
1.2 KiB
C#
45 lines
1.2 KiB
C#
using System.Text.Json.Serialization;
|
|
using OptixServe.Core.Services;
|
|
using OptixServe.Api.Dtos;
|
|
|
|
namespace OptixServe.Api.Endpoints;
|
|
|
|
|
|
[JsonSerializable(typeof(UserDto))]
|
|
[JsonSerializable(typeof(IEnumerable<UserDto>))]
|
|
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 });
|
|
}
|
|
} |