我正在学习ASP.NET,我已经创建了一些简单的API,所以我可以认为自己可能是一个中级初学者。
我决定创建一个用于两个目的的教程:巩固我所学到的知识,并满足对我的语言初学者教程的需求。
我刚刚创建了一个带有CRUD功能的非常简单的API,我想让您回顾一下它。我故意不使用存储库模式和DTO,因为它们可能会让刚刚起步的人感到困惑(至少这是我的经验)。但我确实计划在下一阶段添加这些内容,以及验证和错误处理。
请拆开所有的东西,我需要所有可能的反馈,因为我需要理解我所写的代码的每一行。
主计长:
[ApiController]
[Route("api/records")]
public class RecordsController : ControllerBase
{
private readonly DataContext _context;
public RecordsController(DataContext context)
{
_context = context;
}
[HttpGet]
public ActionResult<IEnumerable<Record>> GetRecords()
{
return _context.Records.ToList();
}
[HttpGet("{id}")]
public ActionResult<Record> GetRecordById(int id)
{
return _context.Records.Find(id);
}
[HttpPost]
public ActionResult<Record> AddRecord([FromBody] Record record)
{
_context.Records.Add(record);
_context.SaveChanges();
return Ok();
}
[HttpDelete("{id}")]
public ActionResult<Record> DeleteRecord(int id)
{
var recordForDeletion = _context.Records.FirstOrDefault(r => r.Id == id);
_context.Records.Remove(recordForDeletion);
_context.SaveChanges();
return Ok();
}
[HttpPut("{id}")]
public ActionResult<Record> UpdateRecord(int id, [FromBody] Record record)
{
var recordForUpdate = _context.Records.FirstOrDefault(r => r.Id == id);
recordForUpdate.Date = record.Date;
recordForUpdate.Name = record.Name;
recordForUpdate.Value = record.Value;
recordForUpdate.Category = record.Category;
recordForUpdate.Type = record.Date;
_context.SaveChanges();
return Ok();
}
}
}DataContext
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public DbSet<Record> Records { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//seed database with dummy data
modelBuilder.Entity<Record>().HasData(
new Record()
{
Id = 1,
Date = "2020-09-30T00:00:01",
Name = "Coles",
Value = 20,
Category = "Groceries",
Type = "Expense"
},
new Record()
{
Id = 2,
Date = "2020-10-01T00:00:01",
Name = "Traslink",
Value = 30,
Category = "Transportation",
Type = "Expense"
},
new Record()
{
Id = 3,
Date = "2020-10-02T00:00:01",
Name = "Cafe 63",
Value = 22,
Category = "Eating Out",
Type = "Expense"
}
);
}
}
}启动:
public class Startup
{
private readonly IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<DataContext>(x =>
x.UseSqlite(_config.GetConnectionString("DefaultConnection")));
```发布于 2020-10-22 15:36:17
此实现与可生产的CRUD API相差甚远.我只想列举一些缺失的东西:
更好地利用状态代码
Id来自用户,并且应该是唯一的(为了能够进行查找),那么如果提供的Id已经存储在数据库中呢?Id不应该来自用户。这就是为什么分离数据库模型和API模型是一个很好的实践。Id没有记录怎么办?在这里你可以找到一张海报,它可以帮助您决定何时使用哪个http状态代码。
https://codereview.stackexchange.com/questions/250987
复制相似问题