[英]ASP.NET Core Web API - 'IRuleBuilderInitial<CustomerTransactionRequestDto, decimal>' does not contain a definition for 'CustomCurrency'
Validation is done in ASP.NET Core-6 Web API using Fluent Validation.使用 Fluent Validation 在 ASP.NET Core-6 Web API 中完成验证。 So, I have this code:所以,我有这段代码:
Custom Validator:自定义验证器:
public static IRuleBuilder<T, string> CustomCurrency<T>(this IRuleBuilder<T, string> ruleBuilder)
{
var options = ruleBuilder
.Matches(@"^\d+.\d{1,2}$")
.WithMessage("Appropriate Currency format should be xxxxxxxxxxx.xx");
return options;
}
DTO:数据传输协议:
public class CustomerTransactionRequestDto
{
public decimal Amount { get; set; }
}
Then the validator:然后是验证器:
public class CustomerTransactionRequestValidator : AbstractValidator<CustomerTransactionRequestDto>
{
public CustomerTransactionRequestValidator()
{
RuleFor(p => p.Amount).CustomCurrency()
.NotEmpty().WithMessage("Amount should be not empty. ERROR!");
}
}
The problem is that I got this error:问题是我收到了这个错误:
Error CS1929 'IRuleBuilderInitial<CustomerTransactionRequestDto, decimal>' does not contain a definition for 'CustomCurrency' and the best extension method overload 'AuthValidatorSettings.CustomCurrency(IRuleBuilder<CustomerTransactionRequestDto, string>)' requires a receiver of type 'IRuleBuilder<CustomerTransactionRequestDto, string>'错误 CS1929“IRuleBuilderInitial<CustomerTransactionRequestDto, decimal>”不包含“CustomCurrency”的定义,最佳扩展方法重载“AuthValidatorSettings.CustomCurrency(IRuleBuilder<CustomerTransactionRequestDto, string>)”需要类型为“IRuleBuilder<CustomerTransactionRequestDto, string>”的接收器'
Then it highlights:然后它突出显示:
RuleFor(p => p.Amount) RuleFor(p => p.Amount)
How do I get this sorted out?我该如何解决这个问题?
Thank you谢谢
The error message hints that types don't match.错误消息提示类型不匹配。 You have a custom validator based on IRuleBuilder<T, string>
while you are trying to chain it to IRuleBuilderInitial<CustomerTransactionRequestDto, decimal>
.当您尝试将其链接到IRuleBuilderInitial<CustomerTransactionRequestDto, decimal>
时,您有一个基于IRuleBuilder<T, string>
的自定义验证器。 You have a custom validator based on string
property, while on the other end a decimal
property.您有一个基于string
属性的自定义验证器,而在另一端有一个decimal
属性。
To fix this, change the type of Amount property from decimal
to string
:要解决此问题,请将Amount属性的类型从decimal
更改为string
:
public class CustomerTransactionRequestDto
{
public string Amount { get; set; }
}
That way, you can use the validators you already defined in CustomCurrency()
like Matches()
which are available for string
properties.这样,您就可以使用您已经在CustomCurrency()
中定义的验证器,例如可用于string
属性的Matches()
。
If decimal
property is not a mistake, then I'd suggest adding support for decimal
in CustomCurrency()
custom validator, like this:如果decimal
属性没有错误,那么我建议在CustomCurrency()
自定义验证器中添加对decimal
的支持,如下所示:
public static IRuleBuilder<T, decimal> CustomCurrency<T>(this IRuleBuilder<T, decimal> ruleBuilder)
{
// TODO: Your validation.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.