gpt4 book ai didi

c# - fluentvalidation 错误消息包含 c# 属性名称而不是客户端 json 属性名称?

转载 作者:太空宇宙 更新时间:2023-11-03 19:51:26 24 4
gpt4 key购买 nike

我有一个 C# WebApi 项目,我正在使用 FluentValidation.WebApi 包来验证客户端输入。

下面是我的模型类代码,它具有名为“IsPremium”的 C# 属性。对于所有客户端,此同一属性的 json 名称为“isLuxury”。

[Serializable, JsonObject, Validator(typeof(ProductValidator))]
public class Product
{
[JsonProperty("isLuxury")]
public bool? IsPremium { get; set; }
}

我的验证器类如下所示:

public class ProductValidator : AbstractValidator<Product>
{
public ProductValidator()
{
RuleFor(product => product.isPremium).NotNull();
}
}

所以对于这样的请求: http://localhost:52664/api/product

请求正文:{ “是奢侈品”:“”

我收到以下错误:

{
"Message": "The request is invalid.",
"ModelState": {
"product.isPremium": [
"'is Premium' must not be empty."
]
}
}

这里的 Fluent 是选择 C# 属性名称,这对客户端来说毫无意义,因为它知道它是“isLuxury”。我如何强制流利地从 json 属性而不是 c# 属性中选择名称,以提供更好的验证,如“'isLuxury' 不能为空。”?

如果不可能,我将不得不重命名我的所有 C# 属性,使其与向所有客户端公开的这些 json 具有相同的名称。如果您有任何其他更好的方法来解决这个问题,请提出建议。

最佳答案

使用OverridePropertyName 方法修改验证器类

public class ProductValidator : AbstractValidator<Product>
{
public ProductValidator()
{
RuleFor(product => product.isPremium).NotNull().OverridePropertyName("isLuxury");
}
}

引用:https://github.com/JeremySkinner/FluentValidation/wiki/d.-Configuring-a-Validator#overriding-the-default-property-name

或者,您可以调用 WithName 方法来做类似的事情。如果您想完全重命名该属性,我会使用 OverridePropertyName 方法。

关于c# - fluentvalidation 错误消息包含 c# 属性名称而不是客户端 json 属性名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38830078/

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