ServiceStack将无效值转换为null而不是抛出ValidationException

时间:2013-05-23 10:59:00

标签: servicestack

假设我们有以下请求对象:

public class UserRequest
{
    public DateTime? Birthday { get; set; }
    public bool DeservesGift { get; set; }
}

并尝试将以下json发布到给定的URL:

{ 
    "Birthday": "A late summer night",
    "DeservesGift": "No way!"
}

我希望有某种例外。相反,该服务会收到UserRequest个实例,生日为null,DeservesGift为false

为什么会这样? 我们怎么知道他们是否试图将Birthday设置为null,这应该导致200 ok,而不是尝试将其设置为其他东西,这会导致400 Bad请求?因为现在我们将生日设置为null并回复200 ok,这是不对的......

1 个答案:

答案 0 :(得分:1)

静态对象JsConfig具有属性ThrowOnDeserializationError,默认为false。将其设置为true将导致上述示例中的SerializationException

JsConfig.cs, line 343->:

    /// <summary>
    /// Gets or sets a value indicating if the framework should throw serialization exceptions
    /// or continue regardless of deserialization errors. If <see langword="true"/>  the framework
    /// will throw; otherwise, it will parse as many fields as possible. The default is <see langword="false"/>.
    /// </summary>
    private static bool? sThrowOnDeserializationError;
    public static bool ThrowOnDeserializationError { }