假设我有这些类(class):
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 验证似乎没有任何与数据库访问相关的注释
最佳答案
我最终使用了流畅的验证 as suggested .这不是执行此操作的最有效方法,但我正在权衡漂亮的错误和简单的代码。
public class WalletCreateDTO
{
[Required]
[MaxLength(20)]
public string Title { get; set; }
[Required]
public int OwnerId { get; set; }
[Required]
public string CurrencyCode { get; set; }
}
public class WalletCreateDTOValidator : AbstractValidator<WalletCreateDTO>
{
public WalletCreateDTOValidator(Data.Database database)
{
this.RuleFor(w => w.OwnerId)
.Must(ownerId => database.Users.Any(user => user.Id == ownerId))
.WithMessage("User does not exist");
this.RuleFor(w=> w.CurrencyCode)
.Must(currencyCode => database.Currencies.Any(currency => currency.Code == currencyCode))
.WithMessage("Currency does not exist");
}
}
--- 致 future 阅读本文的任何人 ---
NuGet 包:FluentValidation.AspNetCore
配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddFluentValidation(config =>
{
config.RegisterValidatorsFromAssembly(typeof(WalletCreateDTO).Assembly);
});
}
注意:这似乎在程序集中注册了所有验证器。比如我把我所有的DTO都放在Api.Dtos目录/命名空间里,貌似都注册了,很方便。
此外,还有 swagger 集成:MicroElements.Swashbuckle.FluentValidation
关于c# - EF 核心 Web API : foreign key validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66856919/