【问题标题】:WebApi2 Controller Post method always receiving null FromBodyWebApi2 Controller Post 方法总是接收 null FromBody
【发布时间】:2020-07-12 00:56:12
【问题描述】:

我的 POST 方法中的 [FromBody] 始终为空。

我已经在 VS2019 中使用最小的应用程序复制了它:

  • 创建项目 ASP.NET Web 应用程序 (.NET Framework)
  • 选择 Web API

这将使用以下方法创建一个带有 ValuesController 类的骨架项目:

public void Post([FromBody] string value)
{
}

我在“IIS Express (Google Chrome)”中运行这个项目并浏览到 https://localhost:44358/api/values,它工作正常并且 Get 方法中的断点被命中。

然后我尝试使用 cUrl 发布数据:

curl --header "Content-Type: application/json" --url https://localhost:44358/api/values --data "wibble"

断点在 VS2019 中被命中,但值为 null(我预期为“wibble”)。

我可以在请求内容中看到长度是 6,这会根据我传递给数据的字符串的长度而变化,但是读取它的调用返回空字符串,或者一个零字节[]。

this.Request.Content.ReadAsStringAsync().Result     ""
this.Request.Content.Headers.ContentType            {application/json}
this.Request.Content.Headers.ContentLength          6

尝试使用 HttpClient 从另一个 C# 应用程序进行 POST 也会显示相同的结果。

我错过了什么?该问题发生在默认的骨架应用程序中,并且每个人都没有抱怨它的事实表明它一定是显而易见的,但是......

更新

我在 Fiddler 中看到了同样的问题,但已经让它与 HttpClient 一起使用:

client.PostAsync<string>(url, "wibble", new JsonMediaTypeFormatter()).Result;

但以下不起作用(接收为空):

client.PostAsync(url, new StringContent("wibble", Encoding.UTF8), new JsonMediaTypeFormatter()).Result;

【问题讨论】:

  • 你能分享一下使用 HttpClient 尝试 POST 的代码吗?

标签: c# curl asp.net-web-api2 dotnet-httpclient


【解决方案1】:

从以下位置更改生成的代码:

public void Post([FromBody] string value) { ... }

到:

public void Post([FromBody] MyClass value) { ... }

现在可以使用标准 cUrl / Fiddler / Javascript / etc POST。

所以我想问题在于尝试将字符串自动转换为对象,这可以解释为什么很多人没有这个问题。

如果您确实想发布文本,自动生成的控制器(看起来应该做您想做的事)不起作用。

要解决这个问题,请将 Post 方法更改为:

public void Post()
{
    string value = Request.Content.ReadAsStringAsync().Result;
    ...
}

现在没有[FromBody] 意味着Request.Content.ReadAsStringAsync() 按预期返回内容。

总结:

[Route("api/values/obj")]
public void Post([FromBody] MyObject value) /* OK */
{
    ...
}

[Route("api/values/str")]
public void Post([FromBody] string value) /* FAIL */
{
    ...
}

[Route("api/values/str2")]
public void Post() /* OK */
{
    string value = Request.Content.ReadAsStringAsync().Result;
    ...
}

从 cUrl 得到以下结果:

curl "http://localhost:59801/api/Values/obj"  --header "Content-Type: application/json" --data "{id:1, name:'Andy'}"

好的

curl "http://localhost:59801/api/Values/str2" --header "Content-Type: text/plain"       --data "wibble"

好的

curl "http://localhost:59801/api/Values/str2" --header "Content-Type: application/json" --data "wobble"

好的

curl "http://localhost:59801/api/Values/str"  --header "Content-Type: text/plain"       --data "wibble"

失败。 Exception '此资源不支持请求实体的媒体类型'text/plain'。'

curl "http://localhost:59801/api/Values/str"  --header "Content-Type: application/json" --data "wobble"

失败。值为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 2015-08-07
    • 2013-02-08
    相关资源
    最近更新 更多