为什么在使用 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