未发送从 Angular 到 .Net 5 webapi 的发布参数

分享于2022年07月17日 angular asp.net-core-webapi 问答
【问题标题】:未发送从 Angular 到 .Net 5 webapi 的发布参数(Post parameter from Angular to .Net 5 webapi are not sent)
【发布时间】:2022-01-23 03:43:27
【问题描述】:

我有一个带有简单控制器和 HttpPost-Action 的 .Net5 Webapi:

[ApiController]
[Route("[controller]")]
public class UploadController : ControllerBase
{
    [HttpPost]
    [Route("codeisvalid")]
    public bool CodeIsValid(string code)
    {
       return code == "dbddhkp";
    }
}

我尝试从 Angular 组件中调用该动作:

this._http.post(http://localhost:29438/upload/codeisvalid', { code: 'wrongcode'}).subscribe(data => {
   this.codeIsValid=data;
   this.codeChecked=true;
});

动作被调用,但“代码”总是 null 。我还尝试将 Action 修改为 public bool CodeIsValid([FromBody] string code) (添加“[FromBody]”),但随后不再调用该方法,而是收到错误 400

“无法将 JSON 值转换为 System.String”

我必须进行哪些更改才能完成这项工作?


【解决方案1】:

没有一个答案对我有用。我终于在我的 C#-Functions 中添加了一点开销。这工作没有错误

public class CodeModel {
   public string Code {get;set;}
}

public bool CodeIsValid ([FromBody]CodeModel codemodel) {
   return codemodel.Code=="dbddhkp";
}

  • 这是正确的解决方案。
  • 如您所述,要解决此类问题,一种解决方案是根据预期数据创建模型类。另一种解决方案是实现并使用自定义纯文本输入格式化程序使数据正确绑定到字符串类型的动作参数,可以参考这个SO线程: stackoverflow.com/questions/67914467/…