【发布时间】:2021-03-30 13:39:45
【问题描述】:
假设我有这些课程:
public class User
{
public int? Id { get; set; }
...
}
public class Wallet
{
public int? Id { get; set; }
public string Title {get; set;}
public User Owner { get; set; }
...
}
public class WalletCreationDTO
{
[Required]
public string Title {get; set;}
[Required]
public int OwnerId { get; set; }
}
[HttpPost]
public async Task<ActionResult> CreateWallet(WalletCreationDto walletDTO) {...}
我必须像这样向前端报告任何错误的参数:
{
"errors": {
"ownerId": "User by Id does not exist",
"title": "Must not exceed 8 characters"
}
}
如何验证 OwnerId?
- 手动查询数据库似乎无效
- 默认的 ASP.NET Core 验证似乎没有任何与数据库访问相关的注释
【问题讨论】:
-
我建议您尝试 FluentValidation。对于服务器端验证,我发现它非常有用。请注意,这不是广告。
-
看起来不错,但在控制器中包含流畅的验证似乎很麻烦,因为我正在使用 dabatase 上下文进行验证
-
您可以创建一个自定义验证器(实现 IValidation)和retrieve the context 进行检查
-
看起来很乱
标签: c# database validation asp.net-core entity-framework-core