0

In my server, I have a function like this

[HttpPost()]
public void Hello([FromBody]int Version)
{
}

I was able to invoke the above API if I omit the [FromBody]int Version parameters

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;

If [FromBody]int Version is included. I get the following error:

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'
s k
  • 4,342
  • 3
  • 42
  • 61

1 Answers1

0

I have found out the answer, in dotnet core 3.x.

  1. use Microsoft.AspNetCore.Mvc.NewtonsoftJson instead of NewtonsoftJson

  2. Add services.AddControllers().AddNewtonsoftJson();

as pointed out in https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-2.2&tabs=visual-studio#jsonnet-support

s k
  • 4,342
  • 3
  • 42
  • 61