【问题标题】:Why is string/json sent in post request to .netcore web api resulting in null?为什么字符串/json 在 post 请求中发送到 .net core web api 导致 null?
【发布时间】: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


【解决方案1】:

首先,您需要用[FromBody] 标记jsonString,以告诉模型绑定器从发布的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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2016-11-21
    • 2018-01-24
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    相关资源
    最近更新 更多