Home > Mobile >  Bad Request (400) for POST request to ASP.NET Core 6, minimal API, sent from Postman
Bad Request (400) for POST request to ASP.NET Core 6, minimal API, sent from Postman

Time:01-12

why I get 400 bad request when testing ASP.NET CORE minimal API app with Postman?

Default VS 2022 ASP.NET core minimal API project, with following method handler:

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

DTO:

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

Windows 10 or Ubuntu curls works fine:

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

response:

"Echo: testing"

But Postman gets 400:

enter image description here

Postman headers:

enter image description here

Edit: Postman response:

It complains that it cannot bind to DTO AnalizeSentenceRequest r

I tried to add [FromBody] attribute to the handler:

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

but it makes no difference.

It works with curl though... So it looks like Postman is messing up with the body, but what it might be?

Full response:

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

CodePudding user response:

Putting a check in the Content-Length checkbox in Postman. Reason being is that the Content-Length header is mandatory for messages with entity bodies, unless the message is transported using chunked encoding. Content-Length is needed to detect premature message truncation when servers crash and to properly segment messages that share a persistent connection.

  •  Tags:  
  • Related