所有文章 > API使用场景 > ASP.NET Core 构建评论基础设施:从接口到控制器完整实战
ASP.NET Core 构建评论基础设施:从接口到控制器完整实战

ASP.NET Core 构建评论基础设施:从接口到控制器完整实战

引言:开启评论模块基础设施构建

在前面的章节中,我们专注于 Stock 实体的 CRUD 实现;本节教程将加速开发进度,实时构建 Comment 相关的基础架构,剥离控制器中的数据访问,采用仓储模式,让控制器更简洁、可维护。


一、定义仓储接口 ICommentRepository

在项目的 Repositories/Interfaces 目录下新建 ICommentRepository.cs,仅声明一条方法以快速搭建框架:

public interface ICommentRepository
{
    Task < IEnumerable < Comment > > GetAllAsync();
}

二、实现 CommentRepository 与 EF Core 调用

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 中注册依赖注入

打开 Program.cs,在 builder.Services 添加仓储实例映射:

builder.Services.AddScoped < ICommentRepository, CommentRepository > ();

确保与 DbContext 的注册顺序合理,便于控制器注入时能够解析。


四、创建 CommentController 并注入仓储

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);
    }
}

五、定义 CommentDto 简化返回结构

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 完成实体到 DTO 映射

新建静态映射类 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());

七、添加测试数据并验证基础 GET 接口

  1. 在 SQL Server Management Studio 中向 Comments 表插入几条测试记录(如 StockId=21)。
  2. 运行 dotnet watch run,打开 Swagger UI,执行 GET /api/comment

    • 确认返回的 JSON 结构为 CommentDto 列表。
    • 若一切正常,即表示基础架构搭建完成,可继续扩展 POST/PUT/DELETE 等操作。

小结

  • 通过仓储模式剥离控制器与数据库交互逻辑。
  • 使用依赖注入注册仓储实现,保证松耦合。
  • 定义DTO 与静态映射,确保 API 返回结构简洁。
  • 完成基础 GET 接口并验证,可作为后续 CRUD 功能的坚实基础。

原文引自YouTube视频:https://www.youtube.com/watch?v=A3tdyk68KAw

#你可能也喜欢这些API文章!

我们有何不同?

API服务商零注册

多API并行试用

数据驱动选型,提升决策效率

查看全部API→
🔥

热门场景实测,选对API

#AI文本生成大模型API

对比大模型API的内容创意新颖性、情感共鸣力、商业转化潜力

25个渠道
一键对比试用API 限时免费

#AI深度推理大模型API

对比大模型API的逻辑推理准确性、分析深度、可视化建议合理性

10个渠道
一键对比试用API 限时免费