.net core Dotnet Core 3.1 Kestrel Web API BadRequest,System.NotSupportedException

.net core Dotnet Core 3.1 Kestrel Web API BadRequest,System.NotSupportedException,.net-core,dotnet-httpclient,kestrel-http-server,.net Core,Dotnet Httpclient,Kestrel Http Server,在我的服务器中,我有这样一个函数 [HttpPost()] public void Hello([FromBody]int Version) { } 如果省略[FromBody]int Version参数,我就能够调用上述API var c = new HttpClient(); var Json = new StringContent(JsonConvert.SerializeObject(new { Version = 123}), Encoding.UTF8, "application/

在我的服务器中,我有这样一个函数

[HttpPost()]
public void Hello([FromBody]int Version)
{
}
如果省略[FromBody]int Version参数,我就能够调用上述API

var c = new HttpClient();
var Json = new StringContent(JsonConvert.SerializeObject(new { Version = 123}), Encoding.UTF8, "application/json")
var Resp = Api.PostAsync("http://MyURL", Json).Result;
如果包含[FromBody]int版本。我得到以下错误:

Request.Body
{Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream}
    CanRead: true
    CanSeek: false
    CanTimeout: false
    CanWrite: false
    Length: '((Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream)Request.Body).Length' threw an exception of type 'System.NotSupportedException'
    Position: '((Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream)Request.Body).Position' threw an exception of type 'System.NotSupportedException'
    ReadTimeout: 'Request.Body.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
    WriteTimeout: '((Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream)Request.Body).WriteTimeout' threw an exception of type 'System.NotSupportedException'

我在DotnetCore3.x中找到了答案

  • 使用Microsoft.AspNetCore.Mvc.NewtonsoftJson而不是NewtonsoftJson

  • 添加services.AddControllers().AddNewtonsoftJson()

  • 正如在