首页 > 解决方案 > 如何在 ResponseStatus.Meta 中包含 ValidationError.CustomState?

问题描述

我的一个验证器中有以下代码:

        RuleFor(foo => foo)
            .Must(foo => foo != null)
            .WithState(bar => new { Baz, Qux });

然后在我的服务中,我有这个:

        var validationResult = new FooValidator().Validate(req.Foo);

        if (!validationResult.IsValid)
        {
            throw validationResult.ToException();
        }

我认为 ValidationError 的 CustomState 将包含在 ResponseStatus.Meta 属性中。然而,事实并非如此。

有没有一种干净的方法可以做到这一点?

标签: servicestackfluentvalidation

解决方案


以前 ServiceStack 仅支持维护一个字符串字典状态,该状态将在 ResponseStatus错误字段 Meta字典下序列化,例如:

RuleFor(foo => foo)
    .Must(foo => foo != null)
    .WithState(bar => new Dictionary<string,string> { ["Baz"] = "Qux" });

将在错误字段 Meta字典中序列化,例如:

response.Errors[0].Meta //= ["Bar"] = "Qux"

这是首选方法,因为在您的 CustomState 中配置的相同将在字典Dictionary<string,string>中按原样序列化。Meta

否则,我刚刚添加了对匿名对象的支持,因此您现在可以使用:

RuleFor(foo => foo)
    .Must(foo => foo != null)
    .WithState(bar => new { Baz = "Qux" });

这将导致相同的序列化响应 DTO。

此更改从 v5.9.3+ 开始可用,现在可在 MyGet 上使用


推荐阅读