转载 未设置[FromForm]致使未能接收到值

原文: https://www.bilibili.com/read/cv14662792/

环境:前端是微信小程序,后端是.net6 webApi

前端代码:

wx.request({
url: app.globalData.serverHttpUrl + "/Comment/",
 method: "DELETE",
 data: {CommentId: e.currentTarget.dataset.commentid, },
header: {'content-type': 'application/x-www-form-urlencoded'},
success: (res) => {}
})

后端代码:

[HttpDelete]
public async Task<JsonResult> DeleteAsync([FromForm] int CommentId)
 {
    if (await _DataCommentRep.DelOneByIdAsync(CommentId) < 1){
       return new JsonResult(new VMResult<string>() { ResultCode = -1, ResultMsg = "S:删除失败", ResultEntity = null }); }
      return new JsonResult(new VMResult<string>() { ResultCode = 0, ResultMsg = "S:删除成功", ResultEntity = null });
  }

注:如后端不使用 “[FromForm]” 则 CommentId 值始终为 0 即取不到值。

此外,需注意后端为 DELETE或GET时,前端如不使用URL传值的方式,应设:

'content-type': 'application/x-www-form-urlencoded'


拓展学习:

 《x-www-form-urlencoded表示什么意思》https://www.jianshu.com/p/a82a9f003e8b

 《[FromBody]与[FromForm]区别》https://www.cnblogs.com/SmallChen/p/17321789.html

猜你喜欢

转载自blog.csdn.net/djk8888/article/details/141190496