【问题标题】:fluentvalidation error message contains c# property name and not client side json property name?fluentvalidation 错误消息包含 c# 属性名称而不是客户端 json 属性名称?
【发布时间】:2016-08-08 13:09:39
【问题描述】:

我有一个 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”。我如何强制 fluent 从 json 属性而不是 c# 属性中选择名称,以提供更好的验证,例如“'isLuxury'不能为空。”?

如果不可能,我将不得不重命名我所有的 C# 属性,使其具有与暴露给所有客户端的这些 json 相同的名称。请建议您是否有其他更好的方法来解决此问题。

【问题讨论】:

  • 你可以通过Overriding the Default Property Name 来使用Json 属性名称。
  • 即使这样也可以部分解决问题,因为我得到了 "product.isPremium": ["'isLuxury' must not be empty."] - 现在 product.isPremium 对 api 的最终用户毫无意义。我也可以改变吗?
  • 知道了,我必须使用 OverridePropertyName。感谢您的帮助。
  • -1,我提到了解决您的问题的方法my answer 对您之前的一个问题。请在提出新问题之前阅读documentation。
  • 是的,我的错.. 没有正确阅读您之前的答案。将确保首先阅读文档。感谢您的指导。

标签: c# json asp.net-web-api fluentvalidation


【解决方案1】:

使用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 方法。

【讨论】:

  • 调用WithName 就足够了,如果您为同一属性调用OverridePropertyName
  • 反之亦然。如果我们想为同一个属性调用 WithName,调用 OverridePropertyName 就足够了。
  • 无论如何,在任何情况下都不需要调用这两个方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
  • 2012-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多