我有一个简单的HTTP POST请求,然后将其发送到使用Kestrel在localhost中运行的ASP Core 2应用程序。除非我从另一个C#应用程序使用null
,否则接收到的数据始终为PostAsJsonAsync
。
我发送的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.案例:通过
PostAsJsonAsync
从另一个C#应用发送在一种情况下,我可以通过另一个使用
PostAsJsonAsync
的单独C#应用程序成功发送请求,如下所示: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.案例:使用外部REST客户端(如Postman)发送
在另一种情况下,我尝试通过另一个REST客户端(例如Postman或通过REST client extension的Visual Studio Code)发送请求:
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字符串(这是完全相同的),以及以下参考文献中提到的其他内容,但是没有任何效果。我想念什么?
其他尝试过的测试/参考
Value are always null when doing HTTP Post requests
Asp.net Core 2 API POST Objects are NULL?
Model binding JSON POSTs in ASP.NET Core
最佳答案
如果要在JSON
中以字符串形式接收API
正文,请在HttpClient
请求中使用以下标头:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
用于将主体作为字符串接收。
// POST: api/NativeClient
[HttpPost]
public async Task<IActionResult> Post([FromBody]string value)
{
[...]
如果您需要将内容作为对象接收,请将此标头添加到您的请求中:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
并像这样更改您的
API
:// POST: api/NativeClient
[HttpPost]
public async Task<IActionResult> Post([FromBody]yourClass class)
{
[...]
将
JSON
对象发送到您的API
:var Content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("/api/NativeClient/", Content);
PostAsJsonAsync
需要一个C#对象将此序列化为JSON
字符串并发送,但是PostAsync
需要一个JSON
字符串来发送。请参阅此问答httpclient-not-supporting-postasjsonasync-method-c-sharp
请参阅此链接以获取更多信息:
PostAsJsonAsync in C#
PostAsync
关于c# - ASP Core 2空POST请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48842953/