c# - 使用 Validator 属性(或替代属性)来验证结构

标签 c# .net .net-core fluentvalidation

我们正在使用 "FluentValidation.AspNetCore": "6.4.0-beta3"Validate 属性适用于类。我们如何将它与结构一起使用?编译器提示:

Attribute 'Validator' is not valid on this declaration type. It is only valid on 'class, parameter' declarations. [netstandard1.6] ValidatorAttribute.ValidatorAttribute(Type validatorType)

[Validator(typeof(FoobarValidator))]
public struct FoobarDto
{
    public string Foo { get; set; }

    public string Bar { get; set; }
}

如果无法在结构上使用 Validate 属性,那么对结构使用流畅验证的替代方法是什么?

最佳答案

我猜编译器很清楚你不能在结构上使用这个注解这一事实。您可以“手动”进行验证:

FoobarDto fooBar = new FoobarDto();
FoobarValidator validator = new FoobarValidator();
ValidationResult results = validator.Validate(fooBar);

或者将您的结构转换为一个类。

关于c# - 使用 Validator 属性(或替代属性)来验证结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41030905/

相关文章:

c# - C#中的接口(interface)冲突解决

c# - 具有 WsFederation 身份验证的 Owin 应用陷入无限重定向循环

c# - 如何使我的 WCF 服务调用通过已配置的本地代理服务器?

javascript - 在为图表动态创建持有者后渲染图表不起作用

C# - 通过反射获取所有程序集及其类型

c# - 使用 LINQ 获取在列表中出现一次的元素的计数

c# - 如何获取app.config中的服务基地址?

c# - Azure Blob 存储 | AcquireLeaseAsync,同步等待直到锁释放

c# - 在单独的程序集中启用带有上下文的迁移?

firebase - 如何通过代理使用 FirebaseAdmin?