【问题标题】:POST data is null with ASP.NET API Controller使用 ASP.NET API 控制器的 POST 数据为空
【发布时间】:2018-04-19 12:05:26
【问题描述】:

我正在尝试迁移到 ASP.NET 6 API 控制器,我的 JS 函数中的 POST 数据显示为空。

我有以下 json 请求:

// searchTerms is an array with 2 properties, Value and Type
$.ajax({
    type: 'Post',
    contentType: 'application/json',
    dataType: "json",
    data: JSON.stringify({
        searchTerms
    })

如果我将其发布到 ASP.NET 6 MVC 控制器:

public ActionResult Search(List<SearchTerm> searchTerms)

然后我的 searchTerms 列表被正确填充。

如果我发布到 API 控制器

[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/search")]
public IHttpActionResult Search([FromBody] List<SearchTerm> searchTerms)

那么 searchTerms 为空。

我试过改contentType,dataType,去掉stringify函数都没用。

我已尝试将签名更改为

public IHttpActionResult Search([FromBody] dynamic value)

看到以下内容,显然我没有正确绑定?

这是我的 SearchTerm 模型:

public class SearchTerm
{
    public string Value { get; set; }
    public string Type { get; set; }
}

【问题讨论】:

  • 您能发布您的 SearchTerm 模型吗?
  • 我认为您传递的模型中包含SearchTerms 列表,而不是直接传递列表。但这只是猜测。

标签: c# asp.net asp.net-mvc


【解决方案1】:

代替:

data: JSON.stringify({
    searchTerms
})

将您的 $.ajax 呼叫更改为仅使用:

data: JSON.stringify(searchTerms)

您正在发送类似于以下内容的 JSON:

{
    "seachTerms": [
        ...
    ]
}

根据我建议的更改,这将只是一个简单的 JSON 数组,应该可以在您的示例中使用。

【讨论】:

  • 快速提问,我现在如何添加其他参数? (即整数)
  • 在这里查看@Nkosi 的回答:stackoverflow.com/a/44599682/2630078,如果有帮助,请务必支持他的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-19
  • 2018-03-30
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多