Testing a WebAPI 2.0 POST with:
(1) Body:
{"Description" : 'a', "Priority" : '1', "IsActive": 'x'}
Is supposed to return:
{"errors": [{
"code": 1020,
"message": "The isActive field must have a value of either true, false"
}]}
(2) Body:
{"Description" : 'a', "Priority" : '1'}
Is supposed to return:
{"errors": [{
"Code": 1010
"Message":"The isActive field is required"
}]}
(3a) Body:
{"Description" : 'a', "Priority" : '1', "IsActive": true}
Is supposed to return an empty body
(3b) Body:
{"Description" : 'a', "Priority" : '1', "IsActive": "true"}
Is supposed to return an empty body
(3c) Body:
{"Description" : 'a', "Priority" : '1', "IsActive": 0}
Is supposed to return an empty body
(3d) Body:
{"Description" : 'a', "Priority" : '1', "IsActive": 1}
Is supposed to return an empty body
(3e) Body:
{"Description" : 'a', "Priority" : '1', "IsActive": "1"}
Is supposed to return an empty body
(3f) Body:
{"Description" : 'a', "Priority" : '1', "IsActive": "0"}
Is supposed to return an empty body
However, the AC says that when IsActive is missing it should be:
This is the field I'm using which is part of the class which represents the Body.
[Required(ErrorMessage = "The isActive field must have a value of either true, false")]
//When IsActive is missing, message should be: The IsActive field is Required
//when IsActive is not the correct type, message should be: The isActive field must have a value of either true, false"
[JsonConverter(typeof(JsonBoolConverter))]
public bool? IsActive { get; set; }
Here's the JsonBoolConverter
public class JsonBoolConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(bool?);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool @return = true;
bool? @nullable = null;
if (reader.Value != null)
{
if (TryConvertToBoolean(reader.Value.ToString(), out @return))
{
@nullable = @return;
}
}
return @nullable;
}
private static readonly List<string> TrueString = new List<string>(new string[] { "true", "1", });
private static readonly List<string> FalseString = new List<string>(new string[] { "false", "0", });
public static bool TryConvertToBoolean(string input, out bool result)
{
// Remove whitespace from string and lowercase
string formattedInput = input.Trim().ToLower();
if (TrueString.Contains(formattedInput))
{
result = true;
return true;
}
else if (FalseString.Contains(formattedInput))
{
result = false;
return true;
}
else
{
result = false;
return false;
}
}
}
If I take the ErrorMessage off the Required attribute, I get 1010 for both. If I add the ErrorMessage to the Required attribute, I get 1020 for both.
Can you suggest how I can I get a different message for these 2 scenarios? I have been looking at this for days.