gpt4 book ai didi

api - FluentValidator 和 JsonPatchDocument

转载 作者:行者123 更新时间:2023-12-04 15:44:49 42 4
gpt4 key购买 nike

我有 WebAPI (.NET Core) 并使用 FluentValidator 来验证模型,包括更新。
我使用 PATCH 动词并有以下方法:

    public IActionResult Update(int id, [FromBody] JsonPatchDocument<TollUpdateAPI> jsonPatchDocument)
{

另外,我有一个验证器类:
public class TollUpdateFluentValidator : AbstractValidator<TollUpdateAPI>
{
public TollUpdateFluentValidator ()
{
RuleFor(d => d.Date)
.NotNull().WithMessage("Date is required");

RuleFor(d => d.DriverId)
.GreaterThan(0).WithMessage("Invalid DriverId");

RuleFor(d => d.Amount)
.NotNull().WithMessage("Amount is required");

RuleFor(d => d.Amount)
.GreaterThanOrEqualTo(0).WithMessage("Invalid Amount");
}
}

并在 Startup 类中映射此验证器:
        services.AddTransient<IValidator<TollUpdateAPI>, TollUpdateFluentValidator>();

但它不起作用。如何为我的任务编写有效的 FluentValidator?

最佳答案

您将需要手动触发验证。
您的操作方法将是这样的:

public IActionResult Update(int id, [FromBody] JsonPatchDocument<TollUpdateAPI> jsonPatchDocument)
{
// Load your db entity
var myDbEntity = myService.LoadEntityFromDb(id);

// Copy/Map data to the entity to patch using AutoMapper for example
var entityToPatch = myMapper.Map<TollUpdateAPI>(myDbEntity);

// Apply the patch to the entity to patch
jsonPatchDocument.ApplyTo(entityToPatch);

// Trigger validation manually
var validationResult = new TollUpdateFluentValidator().Validate(entityToPatch);
if (!validationResult.IsValid)
{
// Add validation errors to ModelState
foreach (var error in validationResult.Errors)
{
ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
}

// Patch failed, return 422 result
return UnprocessableEntity(ModelState);
}

// Map the patch to the dbEntity
myMapper.Map(entityToPatch, myDbEntity);
myService.SaveChangesToDb();

// So far so good, patch done
return NoContent();
}

关于api - FluentValidator 和 JsonPatchDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56344275/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com