gpt4 book ai didi

servicestack - 拦截 Fluent 验证

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

我们正在使用 fluentvalidation(带有服务堆栈)来验证我们的请求 DTO。我们最近扩展了我们的框架以接受“PATCH”请求,这意味着我们现在需要仅在补丁包含要验证的字段时才应用验证。

我们使用这样的扩展方法完成了此操作:

       RuleFor(dto => dto.FirstName).Length(1,30)).WhenFieldInPatch((MyRequest dto)=>dto.FirstName);
RuleFor(dto => dto.MiddleName).Length(1,30)).WhenFieldInPatch((MyRequest dto)=>dto.MiddleName);
RuleFor(dto => dto.LastName).Length(1,30)).WhenFieldInPatch((MyRequest dto)=>dto.LastName);

这意味着我们可以对 POST/PUT 或 PATCH 运行相同的验证。

我一直在寻找一种连接到流畅验证框架的方法,这样我们就不需要在验证的每一行上复制 .WhenFieldInPatch() 规则,但还没有找到一个好的方法做这个。

我尝试了以下方法:

  1. 创建一个辅助方法(在基类中)来拦截初始的“RuleFor”,它在前面添加了 .When() 子句,但这不起作用,因为流畅的验证需要 .When()最后
  2. 拦截PreValidation中的调用,但只能全类拦截,不能逐条拦截
  3. 添加一个扩展方法以应用于每个规则的末尾(根据示例),但我无法访问初始表达式以检查是否应映射该字段 - 因此我需要再次将其传递。<

我是否遗漏了什么,或者我正在尝试不可能的事情?

谢谢

最佳答案

当我需要共享 Fluent Validation Logic 时,我会使用扩展方法,这里是 shared Extension methods for TechStacks 的示例,例如:

public static class ValidatorUtils
{
public static bool IsValidUrl(string arg) => Uri.TryCreate(arg, UriKind.Absolute, out _);
public static string InvalidUrlMessage = "Invalid URL";

public static IRuleBuilderOptions<T, string> OptionalUrl<T>(
this IRuleBuilderInitial<T, string> propertyRule)
{
return propertyRule
.Length(0, UrlMaxLength)
.Must(IsValidUrl)
.When(x => !string.IsNullOrEmpty(x as string))
.WithMessage(InvalidUrlMessage);
}
}

some examples它们的共享位置:

public class CreatePostValidator : AbstractValidator<CreatePost>
{
public CreatePostValidator()
{
RuleSet(ApplyTo.Post, () =>
{
RuleFor(x => x.Url).OptionalUrl();
});
}
}

public class UpdatePostValidator : AbstractValidator<UpdatePost>
{
public UpdatePostValidator()
{
RuleSet(ApplyTo.Put, () =>
{
RuleFor(x => x.Url).OptionalUrl();
});
}
}

关于servicestack - 拦截 Fluent 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61528512/

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