gpt4 book ai didi

c# - POST 方法中来自 JsonSerializer 的 NullReferenceException

转载 作者:行者123 更新时间:2023-11-30 21:26:23 24 4
gpt4 key购买 nike

我试图在#C 中编写一个简单的 REST API,但在编写 POST 处理程序时,我很早就遇到了一个问题,其中包含一条相当无用的错误消息。我使用的是 .NET Core 3.0,该项目是使用 Visual Studio 中的 ASP.NET Core API 模板创建的。

这是我的代码的简化版本,它仍然会触发问题(这些类位于完整项目的单独文件中):

[Route("api/blub")]
[ApiController]
public class BlubController : ControllerBase
{
[HttpGet]
public IEnumerable<Blub> Get()
{
return new Blub[0];
}

[HttpPost]
public ActionResult<Blub> PostBlub([FromBody] string[] paths)
{
return new Blub(paths);
}
}

public class Blub
{
public Blub(string[] paths)
{
this.Paths = paths;
StartedAt = DateTime.Now;
}

public string[] Paths { get; }
public DateTime StartedAt { get; }
}

我的 POST 请求的负载类似于以下内容:

{ "paths": [ "abc", "def" ] }

在对我的 api/blub 路由执行 POST 请求时出现以下异常:

System.NullReferenceException: Object reference not set to an instance of an object.
at System.Text.Json.JsonSerializer.HandleStartObject(JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadCore(JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan`1 buffer, JsonSerializerOptions options, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext)
at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

无论我的 POST 请求是否包含正确的主体,任何 POST 请求似乎都会触发此异常。 GET 请求可以正常工作。我试图登录到控制台并在我的函数中设置一个断点,但据我所知,甚至在我的函数被调用之前就抛出了异常。

为什么 JsonFormatter 会在此处抛出异常,我该如何解决?

最佳答案

类型映射有问题,要么将方法签名更改为:

[HttpPost]
public ActionResult<Blub> PostBlub([FromBody] MyRequest request)
{
return new Blub(request.Paths);
}

public class MyRequest
{
public string[] Paths { get; set; }
}

或将负载更改为:

 [ "abc", "def" ]

关于c# - POST 方法中来自 JsonSerializer 的 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59237795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com