.net core 1.1.0 MVC 控制器接收Json字串 (JObject对象) (一)
.net core 1.1.0 MVC 控制器接收Json字串 (JObject对象) (二)
Json是WEB交互常见的数据,.net core 处理方式是转为强类型,没有对应的强类型会被抛弃,有时我们想自己在后台处理就想获得原始Json串,但.net core客户端的请求进行了默认的封装和转换。浏览器请求get,post,get不发Json,post发送请求有Form键值方式和Body数据方式,把键值对转成Json相对容易,这也是系列(一)的内容。
直接来思路,首先定义自己的ModelBinderProvider 如下:
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; } }
接着编写对应的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; } } }
最后将JObjectModelBinderProvider添加到Startup
services.AddMvc(options =>
{
options.ModelBinderProviders.Insert(0, new JObjectModelBinderProvider());//加入JobjectModelBinderProvider绑定
});
使用
[HttpPost]
public IActionResult ComWizard(JObject data)
{
return new JsonResult(data);
}
web端
$.post("/Home/ComWizard", { UserName: "Jerry", Password: "123" }, function (data) {
alert(data.userName + "--" + data.password);//这是以Form键值对方式提交的,非Json,但在控制器会认为是JObject
});