我有一个数组,我正在使用JSON.stringify转换为JSON
const arrayOfUpdatesAsJSON = JSON.stringify(this.ArrayOfTextUpdates);
这会输出一些有效的JSON。
[{"key":"AgentName","value":"Joe Blogs"},{"key":"AgentEmail","value":"[email protected]"}]
当我要将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填充,但它总是为null。我错过了什么?
首先,您需要使用jsonString
标记[FromBody]
,以告诉模型绑定器绑定来自已发布的json的参数。而且因为你期望普通的string
值你需要传递有效的json string
(而不是object
)所以你需要在javascript中调用额外的JSON.stringify
const jsonArray = JSON.stringify(this.ArrayOfTextUpdates);
const arrayOfUpdatesAsJSON = JSON.stringify(jsonArray);
this.httpservice
.post(
url,
arrayOfUpdatesAsJSON,
httpOptions
)
调节器
[HttpPost("{id:length(24)}", Name = "UpdateLoan")]
public IActionResult Update(string id, [FromBody] string jsonString)