【问题标题】:Post parameter from Angular to .Net 5 webapi are not sent未发送从 Angular 到 .Net 5 webapi 的发布参数
【发布时间】: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<any>(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”

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

【问题讨论】:

标签: angular asp.net-core-webapi


【解决方案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/…
【解决方案2】:

假设所有其他方法都有效,而不是传递一个对象,只需传递'wrongcode'。 C# 期望 传入一个字符串,而不是对象的属性。

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

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 2019-01-04
    • 1970-01-01
    • 2018-07-05
    相关资源
    最近更新 更多