【问题标题】:C# [HttpPost] string value through angular http.post becomes nullC# [HttpPost] 字符串值通过 angular http.post 变为 null
【发布时间】:2019-08-18 20:34:11
【问题描述】:

我的 C# post 方法看起来

[HttpPost]
public void mymethod(string id) {...}

我正在尝试像这样从角度 http.post 发布字符串值,但值到达 C# 方法时为 null。

const mystr = 'mystring';
this.http.post('myurl', mystr);

我尝试了什么

{id: mystr}
JSON.stringify({id: mystr})

注意:使用[HttpGet("{id}")] 发送 id 值效果很好,但 mystr 可能包含 '/' 值,因此只要包含 '/' 就会失败。

当我将我的方法签名替换为([FromBody] string id) 时,我得到400 Bad Request

【问题讨论】:

  • 使用:this.http.post('myurl/'+mystr);
  • mystr 可能包含 '/' 所以它不会一直工作。
  • 然后将其传递到请求正文中,如下所述!
  • 如果你不想声明一个类,那么进入Request-Headers
  • 你能展示一下mystr 的样子吗?

标签: c# json angular angular7


【解决方案1】:

在角度上使用 mystr 上的 encodeValue。在 C# API id 中,你应该得到解码的值。

https://angular.io/api/common/http/HttpUrlEncodingCodec

【讨论】:

  • 简单示例将不胜感激。
  • 我更新了我的答案。我不是角度方面的专家,但一般来说,您需要将斜杠更改为 %2F,这样它们就不会被 C# 视为路径分隔符。
【解决方案2】:

对于您的场景,您需要进行一些小改动,只需在POST 请求中提供您希望接收的数据的Model。 类似的东西:-

public class CustomData {
   string id {get; set;}
}

然后调整你的API,让它知道它必须从request's body接收一些东西

所以,而不是

[HttpPost]
public void mymethod(string id) {...}

使用这个

[HttpPost]
public void mymethod([FromBody] CustomData data) {...}

【讨论】:

  • 我们可以在Angular postmentod中调整一些东西,而不是改变C#方法吗?
【解决方案3】:

您可以尝试更改从角度发送的方式,如下所示

const headers = new HttpHeaders({ 'Content-Type': 'application/json' });

this.http.post('myurl', 'string value', { headers: headers }) ;

如果 'applicaiton/json' 不起作用,请尝试将其更改为 'application/x-www-form-urlencoded'

【讨论】:

  • 我使用 HttpInterceptor 和上面的 HttpHeaders。但没有运气。
猜你喜欢
  • 2015-04-18
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
相关资源
最近更新 更多