I'm new to ASP.Net WebApi. Apologies therefore if this has been asked before (I'm unsure of the correct terminology), but I can only find this related answer which is slightly different to my problem.
I need to create a Post
controller that accepts a complex type (a TestObject
), containing:
- An
IEnumerable<Person>
, wherePerson
has propertiesUsername
andExternalId
- Options on how the controller should handle the data (a
TestOptions
object)
I have defined the classes below with data annotations to assist with validation:
public class TestObject
{
public IEnumerable<TestPerson> TestPerson;
public TestOptions Options;
public void TestOject()
{
this.TestPerson = new List<TestPerson>();
this.Options = new TestOptions();
}
}
public class TestPerson
{
[Required, MaxLength(50)]
public string ExternalId;
[Required, MaxLength(50)]
public string Username;
}
public class TestOptions
{
[Required]
public bool Option1;
[Required, MaxLength(50)]
public string Option2;
}
The controller accepts TestObject
and performs validation before doing anything:
[Route("test")]
public HttpResponseMessage Post([FromBody] TestObject t)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, string.Format("Found {0} people", t.TestPerson.Count().ToString()));
}
}
If I use Fiddler to send a sample JSON object the with correct structures, it works fine. However, if I deliberately introduce errors (E.g. Username
and Option2
missing) like this...
{
"TestPerson":[
{ "ExternalId":"123", "Username":"Bob" },
{ "ExternalId":"123" }
],
"Options":{"Option1":false}
}
I still get
Status 200
2 people found
Why is this happening please? Can I use data annotation validation on complex types?
Update
Debugging image with property values being set: