. NET core 1.1.0 MVC controller receives JSON string (Jobject object) (ii)
. NET core 1.1.0 MVC controller receives JSON string (Jobject object) (one)
The previous article is mainly based on the form key value of the data submitted to JSON processing, sometimes we directly to the body string submitted, we want to solve the following two ways to submit the value of the problem:
Jobject
$ (' #btn_add '). Click (function (e) { var a = $ (' #tb_departments '). Bootstraptable (' getselections '); var post = "{' str1 ': ' Foovalue ', ' str2 ': ' Barvalue '}";//Json.stringify (a); $.ajax ({ type: "POST", URL: "/home/bout", contentType: "Application/json",//Must have DataType: "JSON",/ /indicates the return value type, does not have to data:post,//equivalent to//data: "{' str1 ': ' Foovalue ', ' str2 ': ' Barvalue '}", success:function (data) { //Get Data OK alert (json.tostring (data));});} );
Jarray
$ (' #btn_delete '). Click (function (e) { var a = $ (' #tb_departments '). Bootstraptable (' getselections '); var post = Json.stringify (a); $.ajax ({ type: "POST", URL: "/home/about", contentType: "Application/json",//Must have DataType: "JSON", Represents the return value type and does not have to data:post,//equivalent to//data: "{[{' str1 ': ' Foovalue ', ' str2 ': ' Barvalue '},{' str1 ': ' Foovalue ', ' str2 ': ' Barvalue '}]} ", success:function (data) { //Get Data OK alert (data.id +"--"+data.username); } ); });
There is no valueprovider for body values in. NET core, and this is a factory-mode-based valueprovider that implements the Ivalueproviderfactory interface first:
public class Jobjectvalueproviderfactory:ivalueproviderfactory {public Task createvalueproviderasync (valuepr Oviderfactorycontext controllercontext) {if (ControllerContext = = null) throw new ArgumentNullException ("ControllerContext"); if (ControllerContext.ActionContext.HttpContext.Request.ContentType = = null) {return task.completedtask;}; if (!controllercontext.actioncontext.httpcontext.request.contenttype. StartsWith ("Application/json", StringComparison.OrdinalIgnoreCase)) {return task.completedtask; Not the "Application/json" type is not processed to the original} var bodyText = string. Empty; using (var reader = new StreamReader (controllerContext.ActionContext.HttpContext.Request.Body)) { BodyText = reader. ReadToEnd (). Trim ();//Get Body} if (string. IsNullOrEmpty (BodyText)) {return task.completedtask;} NULL does not handle else {//Add Jobject a valueproviders to process the value CONTROLLERCONTEXT.VALUEPROVIDERS.ADD (new Jobjectvalueprovide R (Bodytext.endswith ("]}")?//Is not a group Jarray.parse (BodyText) as Jcontainer://Is Jarray jobject.parse (body Text) as Jcontainer);//jobject} return task.completedtask; } }
The corresponding Ivalueprovider:
Internal class Jobjectvalueprovider:ivalueprovider { private jcontainer _jcontainer; Public Jobjectvalueprovider (Jcontainer jcontainer) { _jcontainer = Jcontainer; } public bool Containsprefix (string prefix) { // return _jcontainer. Selecttoken (prefix)! = null; return true; } Public Valueproviderresult GetValue (string key) { var jtoken = _jcontainer. Selecttoken (""); if (Jtoken = = null) return valueproviderresult.none; return new Valueproviderresult (Jtoken. ToString (), cultureinfo.currentculture); } }
Register in Startup:
Services. ADDMVC (options = options. Valueproviderfactories.add (New Jobjectvalueproviderfactory ());//value options. Modelbinderproviders.insert (0, New Jobjectmodelbinderprovider ());//Join Jobject binding });
Since the addition of the//jarray type to the. NET core 1.1.0 MVC controller receives the JSON string (Jobject object) (a) Jobjectmodelbinderprovider made a change
public class Jobjectmodelbinderprovider:imodelbinderprovider {public imodelbinder Getbinder ( Modelbinderprovidercontext context) { if (context = = null) throw new ArgumentNullException (nameof (context)); if (context. Metadata.modeltype = = (typeof (Jobject)))//The body holds the data jobject, and the form key value pair { return new Jobjectmodelbinder ( Context. Metadata.modeltype); } if (context. Metadata.modeltype = = (typeof (Jarray)))//jarray support { return new Jobjectmodelbinder (context. Metadata.modeltype); } return null; } }
It is also necessary to modify the Jobjectmodelbinder accordingly to increase support for jobject,jarray and, of course, to write separately
public class Jobjectmodelbinder:imodelbinder {public Jobjectmodelbinder (type type) {if (t Ype = = null) {throw new ArgumentNullException ("type"); }} public Task Bindmodelasync (Modelbindingcontext bindingcontext) {if (BindingContext = = NULL) throw new ArgumentNullException ("BindingContext"); Valueproviderresult result = BindingContext.ValueProvider.GetValue (bindingcontext.modelname);//Call Value Valueprovider try {if (Bindingcontext.modeltype = = typeof (Jobject)) {JO Bject obj = new Jobject (); if (BindingContext.ActionContext.HttpContext.Request.ContentType = = "Application/json")//json { if (result. ToString (). StartsWith ("["))//Is it a group? {obj = (jobject) jarray.parse (result. ToString ()). first;//the first value. Bindingcontext.result = (modelbindingresult.success (obj)); return task.completedtask; } else {obj = Jobject.parse (result. ToString ());//not group direct value}} else//form { foreach (var item in BindingContext.ActionContext.HttpContext.Request.Form) { Obj. ADD (The new Jproperty (item. Key.tostring (), item. Value.tostring ())); }} if ((obj. Count = = 0) {bindingContext.ModelState.TryAddModelError (Bindingcontext.modelna Me, bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor (result. ToString ())); return task.completedtask; } bIndingcontext.result = (modelbindingresult.success (obj)); return task.completedtask; } if (Bindingcontext.modeltype = = typeof (Jarray)) {Jarray obj = new JAr Ray (); if (BindingContext.ActionContext.HttpContext.Request.ContentType. StartsWith ("Application/json", StringComparison.OrdinalIgnoreCase))//json { if (result. ToString (). StartsWith ("["))//Is it a group? {Jarray array = new Jarray (); Array = Jarray.parse (result. ToString ());//Take the first value. Bindingcontext.result = (modelbindingresult.success (array)); return task.completedtask; }} if ((obj. Count = = 0) {bindingContext.ModelState.TryAddModelError (BindingcontExt. ModelName, BindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor (result. ToString ())); return task.completedtask; } Bindingcontext.result = (modelbindingresult.success (obj)); return task.completedtask; } return task.completedtask; } catch (Exception Exception) {if (!) ( Exception is FormatException) && (exception. innerexception = null)) {exception = Exceptiondispatchinfo.capture (exception. innerexception). Sourceexception; } bindingContext.ModelState.TryAddModelError (Bindingcontext.modelname, exception, Bindingcontext.modelmetad ATA); return task.completedtask; } } }
Controller notation form key value pairs, jobject, Jarry Way public iactionresult bout (jarray data)
There are differences in client clients, Jobject, Jarry data must be specified: ContentType: "Application/json",//Must have
When the JSON content is submitted as an array, the controller receives a type of jobject, taking only the first jobject.
. NET core 1.1.0 MVC controller receives JSON string (Jobject object) (ii)