我有一个简单的HTTP POST请求,我发送到使用Kestrel在localhost中运行的ASP Core 2应用程序 . 除非我使用另一个C#应用程序的 PostAsJsonAsync
,否则收到的数据总是 null
.
我发送的 json
有这样的形式:
{
"_isValid": true,
"_username": "test",
"_guid": "f3f574eb-5710-43c5-a4ff-0b75866a72a7",
"_dt": "2018-02-11T15:53:44.6161198Z",
"_ms": "IsSelected"
[...]
}
ASP控制器具有以下形式:
// POST: api/NativeClient
[HttpPost]
public async Task<IActionResult> Post([FromBody]string value)
{
[...]
1. Case: sending with PostAsJsonAsync from another C# app
在一种情况下,我通过另一个单独的C#应用程序成功发送请求,该应用程序使用 PostAsJsonAsync
,如下所示:
HttpClient client = new HttpClient();
client.BaseAddress = new System.Uri("http://localhost:51022/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync("/api/NativeClient/", json);
控制器接收呼叫并成功填充 value
.
2. Case: sending with an external REST client like Postman
在另一种情况下,我尝试通过另一个REST客户端发送请求,例如Postman或Visual Studio Code通过REST client extension:
POST http://localhost:51022/api/NativeClient/ HTTP/1.1
content-type: application/json; charset=utf-8
{
"_isValid": true,
"_username": "gnappo",
"_guid": "f3f574eb-5710-43c5-a4ff-0b75866a72a7",
"_dt": "2018-02-11T15:53:44.6161198Z",
"_ms": "IsSelected"
[...]
}
这里请求由控制器接收,但 string value
始终为 null
.
我已经尝试删除 [FromBody]
标签,检查请求标头,检查正文中的json字符串(完全相同),以及下面引用中提到的其他内容,但没有任何作用 .
我错过了什么?
Other tests tried/references
Value are always null when doing HTTP Post requests
2 回答
如果您希望在
API
中收到JSON
正文作为字符串,请在HttpClient
请求中使用此 Headers :接收体作为字符串 .
如果您需要接收您的内容作为您的对象,请将此标头添加到您的请求中:
并改变你的
API
这样:将
JSON
对象发送到API
:PostAsJsonAsync
需要一个C#对象将其序列化为JSON
字符串并发送,但PostAsync
需要JSON
字符串才能发送 .看到这个问答httpclient-not-supporting-postasjsonasync-method-c-sharp
有关详细信息,请参阅此链接:
PostAsJsonAsync in C#
PostAsync
您应该将
JSON
反序列化为某个模型(类),因为我相信您无论如何都会在代码中的某个位置反序列化此字符串:你的行动:
Regarding to your app:
在你的应用程序中,您将
json
作为参数传递给PostAsJsonAsync()
,但是您需要传递对象并将其解析为JSON
:yourObject
是应该解析为JSON
的类的实例 .After comment:
另外,尝试将您的应用代码更改为: