
深入解析API网关策略:认证、授权、安全、流量处理与可观测性
在前面的章节中,我们专注于 Stock 实体的 CRUD 实现;本节教程将加速开发进度,实时构建 Comment 相关的基础架构,剥离控制器中的数据访问,采用仓储模式,让控制器更简洁、可维护。
在项目的 Repositories/Interfaces
目录下新建 ICommentRepository.cs
,仅声明一条方法以快速搭建框架:
public interface ICommentRepository
{
Task < IEnumerable < Comment > > GetAllAsync();
}
在 Repositories
目录下创建 CommentRepository.cs
,继承 ICommentRepository
并注入 ApplicationDbContext
:
public class CommentRepository : ICommentRepository
{
private readonly ApplicationDbContext _context;
public CommentRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task < IEnumerable < Comment > > GetAllAsync()
{
return await _context.Comments.ToListAsync();
}
}
打开 Program.cs
,在 builder.Services
添加仓储实例映射:
builder.Services.AddScoped < ICommentRepository, CommentRepository > ();
确保与 DbContext 的注册顺序合理,便于控制器注入时能够解析。
在 Controllers
文件夹下新增 CommentController.cs
:
[ApiController]
[Route("api/[controller]")]
public class CommentController : ControllerBase
{
private readonly ICommentRepository _commentRepo;
public CommentController(ICommentRepository commentRepo)
{
_commentRepo = commentRepo;
}
[HttpGet]
public async Task < IActionResult > GetAllAsync()
{
var comments = await _commentRepo.GetAllAsync();
// 后续映射至 DTO
return Ok(commentsDto);
}
}
在 Models/Dto
目录下新建 CommentDto.cs
,复制实体字段并去除导航属性:
public class CommentDto
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime CreatedOn { get; set; }
public int StockId { get; set; }
}
新建静态映射类 CommentMapper.cs
:
public static class CommentMapper
{
public static CommentDto ToDto(this Comment model) => new()
{
Id = model.Id,
Title = model.Title,
Content = model.Content,
CreatedOn = model.CreatedOn,
StockId = model.StockId
};
}
在控制器中,将仓储返回的实体集合通过 LINQ 映射:
var commentsDto = comments.Select(s = > s.ToCommentDto());
Comments
表插入几条测试记录(如 StockId=21)。运行 dotnet watch run
,打开 Swagger UI,执行 GET /api/comment:
CommentDto
列表。原文引自YouTube视频:https://www.youtube.com/watch?v=A3tdyk68KAw