【发布时间】:2019-08-19 06:33:31
【问题描述】:
我有一个数组,我正在使用 JSON.stringify 将其转换为 JSON
const arrayOfUpdatesAsJSON = JSON.stringify(this.ArrayOfTextUpdates);
这会输出一些有效的 JSON。
[{"key":"AgentName","value":"Joe Blogs"},{"key":"AgentEmail","value":"Joe@test.com"}]
因为我要将 JSON 发送到服务器,所以我将内容类型设置为 application/json
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
当按下按钮时,我会使用 url、body 和 header 发出请求。
try {
this.httpservice
.post(
url,
arrayOfUpdatesAsJSON,
httpOptions
)
.subscribe(result => {
console.log("Post success: ", result);
});
} catch (error) {
console.log(error);
}
这工作正常,并达到了我在 api 中期望的方法。
[HttpPost("{id:length(24)}", Name = "UpdateLoan")]
public IActionResult Update(string id, string jsonString)
{
Console.WriteLine(jsonString);
... and some other stuff
}
ID 填充在 url 构建器中,它填充 ok。然后,我希望 api 中的变量 jsonString 的内容用我的请求的 json 填充,但它始终为空。我错过了什么?
【问题讨论】:
-
您正在发送一个数组,但需要查询参数(因为您的控制器上没有定义复杂的模型并且 webapi 不需要
multipart/form-data/application/x-www-form-urlencoded) -
您发送的 JSON 不是字符串。尽管 JSON 实际上是一个“字符串”,但您不能将它直接绑定到 C# 字符串,因为它被解释为一个对象。您需要将其发送为
x-www-form-urlencoded,例如data: { jsonString: JSON.stringify(foo) }。或者,您可以将其绑定到List<KeyValuePair>之类的东西。我不能 100% 确定这会起作用,但它是最接近您发送的 JSON 的构造。
标签: json angular http asp.net-web-api asp.net-core