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
});