【问题标题】:Dotnet Core 3.1 Kestrel Web API BadRequest, System.NotSupportedExceptionDotnet Core 3.1 Kestrel Web API BadRequest、System.NotSupportedException
【发布时间】:2020-02-10 07:18:13
【问题描述】:

在我的服务器中,我有这样的功能

[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 Version。我收到以下错误:

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'

【问题讨论】:

    标签: .net-core dotnet-httpclient kestrel-http-server


    【解决方案1】:

    我在 dotnet core 3.x 中找到了答案。

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

    2. 添加services.AddControllers().AddNewtonsoftJson();

    正如https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-2.2&tabs=visual-studio#jsonnet-support中指出的那样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 2020-12-05
      • 2020-04-23
      相关资源
      最近更新 更多