如何在 ResponseStatus.Meta 中包含 ValidationError.CustomState?

How to include ValidationError.CustomState in ResponseStatus.Meta?

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

        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 属性 中。然而,事实并非如此。

有没有一种干净的方法可以实现这一点?

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

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

将在 Error Field Meta 字典中序列化,例如:

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

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

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

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

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

此更改适用于 v5.9.3+,即现在 available on MyGet