Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 953
JeanD Avatar asked Aug 07 '26 08:08

JeanD


1 Answers

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.

like image 102
Youssef Moussaoui Avatar answered Aug 09 '26 22:08

Youssef Moussaoui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!