【问题标题】:Posted parameter comes up blank in .NET Core 3.0 API.NET Core 3.0 API 中发布的参数为空白
【发布时间】:2020-02-08 09:55:46
【问题描述】:

我创建了 ASP.net core 3.0 Web API 应用程序并添加了HttpPost 端点。

当我使用邮递员向这个 post 端点发帖时,端点没有得到我传递给它的 JSON,而是变为 null。

在 .NET Core 3.0 中是否发生了改变/破坏 HTTP 发布端点的内容?

我发布的 JSON:

{
  "status": "0",
  "operation":"",
  "filter":"",
  "currentOrderList": [
  ]
}

控制器代码:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET: api/<controller>
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<controller>
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/<controller>/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/<controller>/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

我发帖的网址是https://localhost:44336/api/values。我可以看到端点受到了在Visual Studio中调试期间该方法被命中的事实。唯一的问题是参数以 null 的形式传入

【问题讨论】:

  • 我没有投票结束。
  • 你在哪个网址发帖?

标签: c# http-post visual-studio-2019 asp.net-core-3.0


【解决方案1】:

创建一个模型来匹配给定的数据

public class MyClass {
    [JsonProperty("status")]
    public int Status { get; set; }
    [JsonProperty("operation")]
    public string Operation { get; set; }
    [JsonProperty("filter")]
    public string Filter { get; set; }
    [JsonProperty("currentOrderList")]
    public string[] CurrentOrderList { get; set; }
}

然后更新控制器操作以期望所需的类型

//POST api/values
[HttpPost]
public IActionResult Post([FromBody]MyClass value) {
    if(ModelState.IsValid) {
        //...
        return Ok();
    }
    return BadRequest();
}

【讨论】:

  • 我想我的参数大小写或参数类型有问题。 ModelState 的使用是关键
【解决方案2】:

除了像 Nkosi 说的那样添加 [JsonProperty] 注释之外,我还必须添加 nuget 包

Microsoft.AspNetCore.Mvc.NewtonsoftJson

并将.AddNewtonsoftJson() 附加到 Startup.cs。我在另一个 stackoverflow 问题中发现了这一点,但是这两种变化本身都不足以让我的模型水合。两者都让它发挥作用。

services.AddMvc().AddRazorRuntimeCompilation().AddNewtonsoftJson();

【讨论】:

  • 这就是为我做的!我的实际工作没有在模型上添加 [JsonProperty] 属性。我只需要.AddNewtonsoftJson()。这可能是因为我的案例是匹配的(正如 Jay Jay Jay 上面提到的)。
猜你喜欢
  • 1970-01-01
  • 2018-09-24
  • 2018-11-12
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多