我的POST方法中的[FromBody]一直存在问题。
我已经在VS2019中使用最小的应用程序重现了它:
这将使用以下方法使用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(我期望“摆动”)。
我可以在请求内容中看到长度为6,并且该长度根据我传递到数据中的字符串的长度而变化,但是调用读取它会返回空字符串或零的byte []。
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;
但是以下内容不起作用(接收为null):
client.PostAsync(url, new StringContent("wibble", Encoding.UTF8), new JsonMediaTypeFormatter()).Result;
从以下位置更改生成的代码:
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]
now意味着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"
失败。异常'此资源不支持请求实体的媒体类型'text / plain'。
curl "http://localhost:59801/api/Values/str" --header "Content-Type: application/json" --data "wobble"
失败。值为空。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句