【问题标题】:How to use axios.put to send JSON to ASP.NET controller如何使用 axios.put 将 JSON 发送到 ASP.NET 控制器
【发布时间】:2021-03-17 13:05:34
【问题描述】:

我正在尝试使用以下客户端代码发送带有 JSON 数据的 PUT 请求:

const url = new URL(`${process.env.REACT_APP_API}/datas/edit/${id}`);
axios.put(url, data);

在服务器端,当我试图查看HttpRequest.Form 时,控制器会抛出InvalidOperationException 异常。消息是Incorrect Content-Type: application/json;charset=UTF-8

[HttpPut("edit/{id}")]
public void Edit([FromRoute] int id, [FromBody] Data data)
...

我也尝试了axios.put(url, JSON.stringify(data));,但服务器返回 415。

编辑:我尝试使用 Postman 而不是前端:

public class A { public int /*or string*/ A1 { get; set; } }
[HttpPut("edit/{id}")]
public void EditQuestion([FromRoute] int id, [FromBody] A a) ...

重要提示:

我不应该查看 HttpRequest.Form,因为我正在发送 JSON 数据,它应该被解析到我的模型中。

【问题讨论】:

  • 如果你在服务器上发现错误,你会得到更多关于它有什么问题的信息。您能否将服务器上的模型与浏览器发送的模型进行比较(查看浏览器 devtools 网络选项卡,您甚至可以将请求复制为 javascript)。如果您无法弄清楚,您可以同时发布来自 devtools 网络和模型的复制请求吗?
  • 这没什么用,在 Chrome devtools 中,您可以右键单击请求并选择 copy => 作为 fetch 或 curl。该请求可以与服务器上的模型进行比较。
  • A1 发送时不是 int
  • @HMR,我尝试了{ "A1": 1 },尝试更改模型中的字符串。错误是一样的。

标签: asp.net json reactjs put


【解决方案1】:

我看到邮递员的 json 响应返回一个字符串,而不是您的“A”类具有 A1 的 int 属性。

尝试将类更改为:

public class A { public string A1 { get; set; } }

【讨论】:

  • 如果在客户端请求中将 content-type 指定为“application/json”会怎样?
  • 这里也提到了 utf-8。尝试在请求中指定不带编码的内容类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
  • 2012-02-22
  • 1970-01-01
  • 2015-06-25
相关资源
最近更新 更多