.Net5的WebApi中的Post请求,FromBody和FromForm
.Net5的WebApi中的Post请求,FromBody和FromForm
FromBody特性的使用(推荐使用):只能接收单个对象(实体对象或动态类型(dynamic))作参数,无法绑定简单类型(int、string、decimal等)的参数
FromForm特性的使用:接口参数为实体对象或或简单类型参数
FromBody特性的使用(推荐使用):只能接收单个对象(实体对象或动态类型(dynamic))作参数,无法绑定简单类型(int、string、decimal等)的参数
客户端Content-Type是application/json时,接口参数加[FromBody]能正常解析到参数(接口参数为实体对象或动态类型(dynamic)都能解析到参数)
客户端Content-Type是application/x-www-formencoded时,接口参数加或不加[FromBody],接口报415 Unsupported Media Type
客户端Content-Type是multipart/form-data时,接口参数加或不加[FromBody],接口报400 Bad Request
前端代码:
var into = JSON.stringify({ Id: 123, Name: "zsls" });
console.log(into);
$.ajax({
url: "http://localhost:51882/Test/SetParams",
data: into,
type: "post",
//application/x-www-formencoded、multipart/form-data、application/json
contentType: "application/json",
dataType: "json",
success: function (res) {
console.log("success===============" + res);
},
error: function (xhr, textStatus, errorThrown) {
console.log("error===============" + xhr.responseText);
}
});
后端代码:
/// <summary>
/// 学生信息
/// </summary>
public class Student
{
/// <summary>
/// 学生Id
/// </summary>
public int Id { get; set; }
/// <summary>
/// 学生姓名
/// </summary>
public string Name { get; set; }
}
[HttpPost]
public IActionResult SetParams([FromBody] Student stu)
{
return Content("OK");
}
[HttpPost]
public IActionResult SetParams1([FromForm] dynamic obj)
{
return Content("OK");
}
FromForm特性的使用:接口参数为实体对象或或简单类型参数
客户端Content-Type是multipart/form-data时(ajax指定contentType为false,axios指定Content-Type为multipart/form-data),以FormData格式提交数据接口参数加[FromForm]能正常解析到参数(接口参数为实体对象或或简单类型参数都能解析到参数)
前端代码:
var formData = new FormData();
formData.append("id", 12);
formData.append("name", "fls");
$.ajax({
url: "http://localhost:51882/Test/SetParams",
data: formData,
type: "post",
processData: false,
contentType: false,
dataType: "json",
success: function (res) {
console.log("success===============" + res);
},
error: function (xhr, textStatus, errorThrown) {
console.log("error===============" + xhr.responseText);
}
});
后端代码:
/// <summary>
/// 学生信息
/// </summary>
public class Student
{
/// <summary>
/// 学生Id
/// </summary>
public int Id { get; set; }
/// <summary>
/// 学生姓名
/// </summary>
public string Name { get; set; }
}
[HttpPost]
public IActionResult SetParams([FromForm] int id, [FromForm] string name)
{
return Content($"OK,{id},{name}");
}
[HttpPost]
public IActionResult SetParams1([FromForm] Student stu)
{
return Content("OK");
}
原文链接:https://blog.csdn.net/weixin_52437470/article/details/113726646