NETCORE - 请求方式
.Net Core中Get请求接口的参数一般可以在url中获取,但是Post请求接口一般建议使用[FromBody]特性来绑定参数,而前端发请求时也得需要注意,前端代码如下(vue):
-
const postData = {
-
id: 12
-
}; // post请求的数据,可自行定义
-
this.$axios({
-
url: api.postUrl,
-
method: 'post',
-
params: postData
-
}).then((result) => {
-
this.$message({
-
message: '请求成功',
-
type: 'success',
-
showClose: true
-
});
-
}).catch((err) => {
-
this.$message({
-
message: '请求失败',
-
type: 'error',
-
showClose: true
-
});
-
})
-
复制代码
后端代码如下(.Net Core):
-
[HttpPost]
-
public ActionResult HandlePost(int id) {
-
return Content(id);
-
}
-
复制代码
FromBody特性的使用
如果使用上述方法请求,会发现id可以正常获取,因为axios以params方式提交post参数时,默认将参数放在url后面,而后端接口的参数中如果不加其他参数验证的注解,则会默认从url中寻找参数。而如果在接口的参数验证中加[FromBody]注解时,由于[FromBody]注解无法绑定简单类型的参数,因此将参数的类型改成dynamic,其中dynamic类型为动态类型,和Object类型类似,所以需要使用obj. id的方式来获取参数,即代码如下:
-
[HttpPost]
-
public ActionResult HandlePost([FromBody] dynamic obj) {
-
return Content(obj.id);
-
}
-
复制代码
再次请求会发现后端报错415 UnSupported Media Type,因为当以params方式提交post参数时,请求头中无Content-Type字段,Axios源码中对请求做了处理,如下图:
由此可知当使用params方式提交post参数时,即data参数为空时,即使手动设置请求头的Content-Type也会被清除,所以后端代码由于无法识别Content-Type字段,导致报错415 UnSupported Media Type。 为了解决这个问题,则可以将post提交参数的方式改成data方式提交,代码如下:
-
const postData = {
-
id: 12
-
}; // post请求的数据,可自行定义
-
this.$axios({
-
url: api.postUrl,
-
method: 'post',
-
data: postData
-
}).then((result) => {
-
this.$message({
-
message: '请求成功',
-
type: 'success',
-
showClose: true
-
});
-
}).catch((err) => {
-
this.$message({
-
message: '请求失败',
-
type: 'error',
-
showClose: true
-
});
-
})
-
复制代码
然后再次请求会发现成功返回传的id参数值。
这里需要注意的是FromBody特性只接受Content-Type为application/json的请求,只有这样参数才能正确绑定,而axios的post请求中Content-Type默认为application/json, 如果在上述前端代码中手动修改请求头为application/x-www-formencoded或者multipart/form-data,则后台接口又会报错415 UnSupported Media Type.
FromForm特性的使用
FromForm特性和FromBody特性的区别是:FromForm特性是用来绑定form-data格式中的表单数据,即Content-Type为multipart/form-data,所以前端代码应修改为如下:
-
let formData = new FormData();
-
formData.append('id', 1212);
-
this.$axios({
-
url: api.postUrl,
-
method: 'post',
-
// 手动设置Content-Type为form-data格式
-
headers: {
-
'Content-Type': 'multipart/form-data'
-
},
-
data: formData
-
}).then((result) => {
-
this.$message({
-
message: '请求成功',
-
type: 'success',
-
showClose: true
-
});
-
}).catch((err) => {
-
this.$message({
-
message: '请求失败',
-
type: 'error',
-
showClose: true
-
});
-
})
-
复制代码
后端代码修改为如下
-
[HttpPost]
-
public ActionResult HandlePost([FromForm] int id) {
-
return Content(id);
-
}
-
复制代码
FromForm特性没有对简单类型的参数进行限制,所以可以直接获取参数,当formData中有多个参数需要绑定时,可以写成如下格式:
-
[HttpPost]
-
public ActionResult HandlePost([FromForm] int id, [FromForm] string name, ....) { // 只需要增加参数的个数就可以
-
return Content(id);
-
}
-
复制代码
转载于:https://juejin.im/post/5cdab497e51d453adf1fa729
https://blog.csdn.net/weixin_34129145/article/details/91441753
引用:https://www.cnblogs.com/shy1766IT/p/5237164.html