[英]C# FluentValidation not getting triggered
I have a class library with DTOs.我有一个带有 DTO 的 class 库。 For this DTOs I want to use FluentValidation to ensure that the inputs from the user are correct.对于这个 DTO,我想使用 FluentValidation 来确保用户的输入是正确的。
Example: I have a DTO named AddValidationDTO in my class library示例:我的 class 库中有一个名为 AddValidationDTO 的 DTO
namespace MYCoolProjApi.Model.DTOs.Validation {
public class AddWstValidationDTO
{
public string? Name { get; set; }
public string? Regex { get; set; }
public string? AddedOrEditedBy { get; set; }
}
public class AddValidationDTOValidator : AbstractValidator<AddValidationDTO>
{
public WstAddValidationDTOValidator()
{
RuleFor(x => x.Name).NotNull().NotEmpty().WithMessage("Validation Name can't be null");
RuleFor(x => x.Regex).NotNull().NotEmpty().WithMessage("Regex can't be null");
}
}
}
In my main project which is an ASP.NET Web Api I installed the FluentAPI Nuget package too and added this code to my Program.cs:在我的主项目 ASP.NET Web Api 中,我也安装了 FluentAPI Nuget package 并将此代码添加到我的 Program.cs 中:
builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddFluentValidationClientsideAdapters();
builder.Services.AddValidatorsFromAssemblyContaining<AddValidationDTOValidator>();
When I send a request to the enpoint where a new Validation should be created with a faulty DTO I don't get an error and it gets saved to the database.当我向应该使用错误 DTO 创建新验证的 enpoint 发送请求时,我没有收到错误并将其保存到数据库中。 This is the JSON which I send to the controller:这是我发送到 controller 的 JSON:
{
"Name": "",
"AddedOrEditedBy": "MyUser"
}
ValidationController:验证控制器:
[HttpPost("Add")]
public async Task<IActionResult> AddValidation([FromBody] AddValidationDTO validationDTO)
{
await _validationService.AddValidation(validationDTO);
return Ok();
}
[HttpPost]
public IActionResult Create(ValidationDto dto)
{
if(! ModelState.IsValid)
{
// re-render the view when validation failed.
}
//do valid stuff
return RedirectToAction("Index");
}
You add new class like:您添加新的 class,例如:
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.ModelState.IsValid)
{
//Do something you want
}
}
}
and then add attribute to your action然后将属性添加到您的操作
[HttpPost]
[ValidationActionFilter]
public IActionResult Create(ValidationDto dto)
{
...
Remember to register this if you are using DI如果你使用 DI,记得注册这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.