JeanD
JeanD

Reputation: 523

POST object in .NET WebAPI

I have a small problem with the WebApi.

Problem: If I want to post a model using JSON, I can add as many members I want, as long as the members defined in model are present.

Question: How can I trigger an exception, if an undefined member is present in my Json object. Is this achievable without a custom JsonConverter? What I'm looking for is a generic solution, not a convertion for every different model.

Example:

Model:

public class Person
{
    [Required]
    public string Name { get; set; }
}

Api Controller:

public class PersonController : ApiController
{
    public HttpResponseMessage Post(Person person)
    {
        if (person != null)
        {
            if (ModelState.IsValid)
            {
                //do some stuff
                return new HttpResponseMessage(HttpStatusCode.OK);
            }
        }
        return new HttpResponseMessage(HttpStatusCode.BadRequest);

    }
}

Json posts (body) {"Name":"Joe"} --> valid {"Name":"Joe","InvalidMember","test","Name","John"} --> also valid. In this case I want to trigger an Exception. Because if you look at it, it doesn't match my modeldefinition exactly.

Upvotes: 3

Views: 3304

Answers (1)

Youssef Moussaoui
Youssef Moussaoui

Reputation: 12395

One thing you could try is playing around with this setting:

config.Formatters.JsonFormatter.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;

It should give you an invalid model state when there are extra properties that aren't recognized in the JSON.

Upvotes: 3

Related Questions