Vegar
Vegar

Reputation: 12898

ServiceStack converts invalid values into null instead of throwing ValidationException

Lets say that we have the following request object:

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

And try to post the following json to the given url:

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

I would expect an exception of some kind. Instead, the service receives a UserRequest instance with null for Birthday and false for DeservesGift.

Why is this?
How can we know if they tried to set the Birthday to null, which should result in a 200 ok, versus an attempt to set it to something else, which should result in a 400 Bad request? Cause now we will set the birthday to null and respond 200 ok, and that ain't right...

Upvotes: 1

Views: 154

Answers (1)

Vegar
Vegar

Reputation: 12898

The static object JsConfig has a property ThrowOnDeserializationError which defaults to false. Setting it to true will cause a SerializationException in the examples above.

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 { }

Upvotes: 1

Related Questions