在.Net core中,当使用ajax提交json数据时,因为在.net core中是属于强类型数据,所以在数据接受时可以使用[FromBody]标签采用自定义注册的方法,其代码参考如下
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;
}
}
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;
}
}
}
在start.cs中configure添加注册
services.AddMvc(options =>
{
options.ModelBinderProviders.Insert(0, new JObjectModelBinderProvider());//加入JobjectModelBinderProvider绑定
});
在后台接受是如下
[HttpPost]
public stringLogin([FromBody]JObject data)
{
return "";
}
前端传输数据如下:
$.post({
data: {
username: username, password: pwd
},
dataType: "text",
url: "/Home/LogOn",
success: function (result) {}});
当不使用服务注册的方式时。后台使用对象接受,前端使用json,代码如下:将会自动转换成对象的相应属性:
后端接受数据如下所示:
[HttpPost]
public string LogOn(base_userinfo user)
{
return "";
}
前端传输数据如下所示:
$.post({
data: {
username: username, password: pwd
},
dataType: "text",
url: "/Home/LogOn",
success: function (result) {}});