1

为什么在使用 Postman 测试 ASP.NET CORE 最小 API 应用程序时收到 400 个错误请求?

默认 VS 2022 ASP.NET 核心最小 API 项目,具有以下方法处理程序:

app.MapPost("/test", (AnalizeSentenceRequest r) =>
{
    return Results.Ok($"Echo: {r.Sentence}");
});

DTO:

public class AnalizeSentenceRequest
{
    public string? Sentence { get; set; }
}

Windows 10 或 Ubuntu 卷曲工作正常:

> curl -X POST http://localhost:5050/test -H "Content-Type: application/json" -d "{\"sentence\":\"testing\"}"

回复:

“回声:测试”

但是邮递员得到 400:

在此处输入图像描述

邮递员标头:

在此处输入图像描述

编辑:邮递员回复:

它抱怨它无法绑定到 DTO AnalizeSentenceRequest r

我尝试将 [FromBody] 属性添加到处理程序:

([FromBody] AnalizeSentenceRequest r) => ...

但这没有什么区别。

虽然它适用于卷曲......所以看起来邮递员正在搞乱身体,但它可能是什么?

完整回复:

Microsoft.AspNetCore.Http.BadHttpRequestException: Required parameter "AnalizeSentenceRequest r" was not provided from body.
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.Log.RequiredParameterNotProvided(HttpContext httpContext, String parameterTypeName, String parameterName, String source, Boolean shouldThrow)
   at lambda_method1(Closure , Object , HttpContext , Object )
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.<>c__DisplayClass46_3.<<HandleRequestBodyAndCompileRequestDelegate>b__2>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Host: localhost:5050
Content-Type: application/json
4

1 回答 1

2

在 Postman 中勾选 Content-Length 复选框。原因是 Content-Length 标头对于具有实体主体的消息是强制性的,除非使用分块编码传输消息。需要 Content-Length 来检测服务器崩溃时过早的消息截断,并正确分割共享持久连接的消息。

于 2022-01-12T13:25:05.953 回答