Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine when invalid JSON key/value pairs are sent in a .NET MVC request

Tags:

I have a client with a MVC application that accepts raw JSON requests. The ModelBinder maps incoming key/value pairs to the Controller Model properties, no problem there.

The problem is they want to throw an error when they send an invalid key/value pair, and for the life of me I cannot find the raw incoming data.

For example, if I have a model with a string property MName but in their JSON request they send "MiddleName":"M", the ModelBinder will toss this invalid key and leave the MName property blank. This does not throw an error and ModelState.IsValid returns true.

I know that I could throw a [Required] attribute on the property, but that's not right, either, since there might be null values for that property, and still doesn't get to the problem of detecting key/value pairs that don't belong.

This isn't a question of over-posting; I'm not trying to prevent an incoming value from binding to the model. I'm trying to detect when an incoming value just didn't map to anything in the model.

Since the values are coming in as application/json in the request body, I'm not having luck even accessing, let along counting or enumerating, the raw request data. I can pull name/value pairs from ModelState.Keys but that only includes the fields that were successfully mapped. None of these keys are in the Request[] collection.

And yes, this is in ASP.NET MVC 5, not WebApi. Does WebAPI handle this any differently?

Any ideas?

Example:

application/json: { "FName":"Joe", "MName":"M", "LName":"Blow" }

public class PersonModel
{
    public string FName { get; set; }
    public string LName { get; set; }
}

public class PersonController() : Controller
{
    public ActionResult Save(PersonModel person)
    {
        if(ModelState.IsValid) // returns true
        // do things
        return View(person)
    }
}