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


i have client mvc application accepts raw json requests. modelbinder maps incoming key/value pairs controller model properties, no problem there.

the problem want throw error when send invalid key/value pair, , life of me cannot find raw incoming data.

for example, if have model string property mname in json request send "middlename":"m", modelbinder toss invalid key , leave mname property blank. not throw error , modelstate.isvalid returns true.

i know throw [required] attribute on property, that's not right, either, since there might null values property, , still doesn't problem of detecting key/value pairs don't belong.

this isn't question of over-posting; i'm not trying prevent incoming value binding model. i'm trying detect when incoming value didn't map in model.

since values coming in application/json in request body, i'm not having luck accessing, let along counting or enumerating, raw request data. can pull name/value pairs modelstate.keys includes fields mapped. none of these keys in request[] collection.

and yes, in asp.net mvc 5, not webapi. webapi handle 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         // things         return view(person)     } } 

you can read json data sent in request request.inputstream , deserialize object. can compare property names posted property names of model

public actionresult save(personmodel person) {     // models property names     var modelproperties = person.gettype().getproperties().select(x => x.name);    // read inputstream     streamreader reader = new streamreader(request.inputstream);     reader.basestream.position = 0;     string jsontext = reader.readtoend();     // deserialize object , read property names     javascriptserializer serializer = new javascriptserializer();     object jsonobject = serializer.deserializeobject(jsontext);     idictionary<string, object> dictionary = jsonobject idictionary<string, object>;     var jsonproperties = jsonobject.keys;     // json property names not match model property names     list<string> invalidproperties = jsonproperties.except(modelproperties, stringcomparer.ordinalignorecase).tolist(); 

if invalidproperties contains values, throw error (and perhaps use string.join() include list of invalid property names , list of actual model property names in error message returned client).


Comments

Popular posts from this blog

Add new key value to json node in java -

javascript - Highcharts Synchronized charts with missing data points -

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -