[英]EF Core Web API: foreign key validation
假設我有這些課程:
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"
}
}
我如何 go 關於驗證 OwnerId?
我最終按照建議使用了流利的驗證。 這不是最有效的方法,但我正在權衡漂亮的錯誤和簡單的代碼。
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");
}
}
--- To anyone reading this in the future ---
NuGet package: FluentValidation.AspNetCore
配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddFluentValidation(config =>
{
config.RegisterValidatorsFromAssembly(typeof(WalletCreateDTO).Assembly);
});
}
注意:這似乎注冊了程序集中的所有驗證器。 比如我所有的DTO都在Api.Dtos目錄/命名空間里,好像都注冊了,很方便。
此外,還有 swagger 集成: MicroElements.Swashbuckle.FluentValidation
您可以在簡單模式下使用它。
[HttpPost]
public async Task<ActionResult> CreateWallet(WalletCreationDto walletDTO)
{
bool isValidOwnerId = /*validationLogic => can use service or Repository or etc... */
if (isValidOwnerId == false)
ModelState.AddModelError("OwnerId", "errorMessage");
if (ModelState.IsValid)
{
//CreateWallet Loigc......
}
//we can get all errors from ModelState
List<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors).ToList();
/*
return ....
*/
}
我還建議您閱讀以下兩個鏈接。
fluentvalidation :流行的 .NET 庫,用於構建強類型驗證規則。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.