【发布时间】: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