PostAsJsonAsync发布null

时间:2019-11-14 11:18:29

标签: asp.net-core dotnet-httpclient

我正在尝试使用PostAsJsonAsync发布对象,但在接收API处始终为null。调用代码在这里:

    public async Task UploadDocument(FileDto model)
    {
        var response = await _httpClient.PostAsJsonAsync("file/UploadDocument", model);
        response.EnsureSuccessStatusCode();
    }

接收代码的签名在这里:

    [HttpPost]
    [Route("UploadDocument")]
    public async Task<IHttpActionResult> UploadDocument(FileDto document)

FileDto在两个项目中都是相同的,并且只包含一个字符串属性“ FileName”

问题在于文档始终为空。

我可以使用工作正常的PostAsync:

    public async Task UploadDocument(FileDto model)
    {
        string inputJson = Newtonsoft.Json.JsonConvert.SerializeObject(model);
        HttpContent inputContent = new StringContent(inputJson, Encoding.UTF8, "application/json");
        var response = await _httpClient.PostAsync("file/UploadDocument", inputContent);
        response.EnsureSuccessStatusCode();
    }

在第一个(不起作用的)示例中,看Fiddler,请求看起来像这样:

POST http://localhost:59322/api/file/UploadDocument HTTP/1.1
Accept: application/json
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Host: localhost:59322

28
{"FileName":"File-0000004157.jpg"}
0

第二个(有效的)示例在Fiddler中如下所示:

POST http://localhost:59322/api/file/UploadDocument HTTP/1.1
Accept: application/json
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Host: localhost:59322


{"FileName":"File-0000004157.jpg"}

第一个示例似乎添加了额外的文本-参见“ 28”和“ 0”。

此文字来自何处。我可以使用PostAsync,但是在PostAsJsonAsync为您添加额外的代码时似乎很遗憾。

有人有什么主意吗?

2 个答案:

答案 0 :(得分:0)

在asp.net核心中,您需要返回IActionResult而不是IHttpActionResult

[HttpPost]
[Route("UploadDocument")]
public async Task<IActionResult> UploadDocument(FileDto document)
{
    return Ok(document);
}

https://docs.microsoft.com/en-us/aspnet/core/migration/webapi?view=aspnetcore-3.0

ASP.NET Core Web Api Error for IhttpActionResult

答案 1 :(得分:0)

.net core 中的 PostAsJsonAsync 似乎存在问题:它返回 content-length 为 0,导致接收端忽略声明的空主体。< /p>

https://github.com/aspnet/AspNetWebStack/issues/252

HttpClient PostAsJsonAsync behaving different in .NET Core and Classic .NET

解决方法是使用... PostAsync