. Net core 1.1.0 MVC controller receives Json strings (JObject object) (1), jsonjobject
. Net core 1.1.0 MVC controller receives Json strings (JObject object) (2)
Json is a common data for WEB interactions ,. net core is converted to a strong type, and no corresponding strong type will be discarded. Sometimes we want to obtain the original Json string for processing in the background,.. net core client requests are encapsulated and converted by default. The browser requests get, post, get without sending Json. The Form and Body data methods are used for post sending requests. It is relatively easy to convert the key-value pairs into Json, which is also a Series (1).
First, define your own ModelBinderProvider as follows:
public class JObjectModelBinderProvider : IModelBinderProvider { public IModelBinder GetBinder(ModelBinderProviderContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); if (context.Metadata.ModelType == (typeof(JObject))) { return new JObjectModelBinder(context.Metadata.ModelType); } return null; } }
Then write the corresponding ModelBinder
public class JObjectModelBinder : IModelBinder { public JObjectModelBinder(Type type) { if (type == null) { throw new ArgumentNullException("type"); } } public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) throw new ArgumentNullException("bindingContext"); ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); try { JObject obj = new JObject(); if (bindingContext.ModelType == typeof(JObject)) { foreach (var item in bindingContext.ActionContext.HttpContext.Request.Form) { obj.Add(new JProperty(item.Key.ToString(), item.Value.ToString())); } 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.ModelMetadata); return Task.CompletedTask; } } }
Add JObjectModelBinderProvider to Startup.
Services. AddMvc (options =>
{
Options. ModelBinderProviders. Insert (0, new JObjectModelBinderProvider (); // bind to JobjectModelBinderProvider
});
Use
[HttpPost]
Public IActionResult ComWizard (JObject data)
{
Return new JsonResult (data );
}
Web end
$. Post ("/Home/ComWizard", {UserName: "Jerry", Password: "123"}, function (data ){
Alert (data. userName + "--" + data. password); // This is submitted in Form key-value pairs, not Json, but is considered as JObject in the Controller
});