为什么字符串/json在post请求中发送到.netcore web api会导致null?

为什么字符串/json在post请求中发送到.netcore web api会导致null?,json,angular,http,asp.net-web-api,asp.net-core,Json,Angular,Http,Asp.net Web Api,Asp.net Core,我有一个使用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 h

我有一个使用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、正文和标题发出请求

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生成器中填充,url生成器填充ok。然后,我希望api中变量jsonString的内容填充请求的json,但它总是空的。我遗漏了什么?

首先,您需要用
[FromBody]
标记
jsonString
,告诉model binder从发布的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)

您发送的是一个数组,但需要查询参数(因为控制器上没有定义复杂的模型,而且webapi不需要
多部分/表单数据
/
应用程序/x-www-form-urlencoded
),所以您发送的是JSON而不是字符串。即使JSON实际上是一个“字符串”,也不能将其直接绑定到C#字符串,因为它被解释为一个对象。您需要将其作为
x-www-form-urlencoded
发送,如
数据:{jsonString:JSON.stringify(foo)}
。或者,您可以将其绑定到类似于
List
的内容。我不是100%确定这会起作用,但这是与您发送的JSON最接近的构造。