比-httpvsWebSocket-API.png)
HTTP API vs WebSocket API:選擇哪個(gè)來實(shí)現(xiàn)實(shí)時(shí)通信?
在項(xiàng)目的 Repositories/Interfaces
目錄下新建 ICommentRepository.cs
,僅聲明一條方法以快速搭建框架:
public interface ICommentRepository
{
Task < IEnumerable < Comment > > GetAllAsync();
}
在 Repositories
目錄下創(chuàng)建 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
添加倉(cāng)儲(chǔ)實(shí)例映射:
builder.Services.AddScoped < ICommentRepository, CommentRepository > ();
確保與 DbContext 的注冊(cè)順序合理,便于控制器注入時(shí)能夠解析。
在 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();
// 后續(xù)映射至 DTO
return Ok(commentsDto);
}
}
在 Models/Dto
目錄下新建 CommentDto.cs
,復(fù)制實(shí)體字段并去除導(dǎo)航屬性:
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; }
}
新建靜態(tài)映射類 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
};
}
在控制器中,將倉(cāng)儲(chǔ)返回的實(shí)體集合通過 LINQ 映射:
var commentsDto = comments.Select(s = > s.ToCommentDto());
Comments
表插入幾條測(cè)試記錄(如 StockId=21)。運(yùn)行 dotnet watch run
,打開 Swagger UI,執(zhí)行 GET /api/comment:
CommentDto
列表。原文引自YouTube視頻:https://www.youtube.com/watch?v=A3tdyk68KAw
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)