Pete
Pete

Reputation: 3451

Posting Boolean to ASP.NET Core 5 Controller Fails for "true" but not true

I do a post request using curl as follows to an asp.net core 5 controller

curl -d "{\"sponsorOnly\":\"true\", \"id\":\"101\"}" -H "Content-Type: application/json" -X POST http://localhost:5000/rpc/Email/EmailGenerate

It gives me the following error:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-7b45947384087a49b8b37125f7424172-a0e14922a4546649-00",
  "errors": {
    "$.sponsorOnly": [
      "The JSON value could not be converted to System.Boolean. Path: $.sponsorOnly | LineNumber: 0 | BytePositionInLine: 21."
    ]
  }
}

When I remove the quotes from "true" and make it just true, it works and my controller gets the proper boolean value. Here is the curl that works:

curl -d "{\"sponsorOnly\":true, \"id\":\"101\"}" -H "Content-Type: application/json" -X POST http://localhost:5000/rpc/Email/EmailGenerate

I have my asp.net core 5 controller as follows:

[ApiController]
public class EmailController : ControllerBase
{
    [HttpPost("/rpc/Email/EmailGenerate")]
    public object Post(EmailSendDetail emailSendDetail)
    {
        return new OkResult();
    }...

and EmailSendDetail as

public class EmailSendDetail
{
    public int Id { get; set; }
    public bool SponsorOnly { get; set; }
}

This use to work (gives me booleans passed into POST method) in ASP.NET but does not in ASP.NET Core.

Upvotes: 1

Views: 2195

Answers (1)

poke
poke

Reputation: 388103

As Camilo Terevinto already mentioned in the comments, this scenario is not supported. The new default JSON serializer in ASP.NET Core 3.x and later will not parse the strings "true" and "false" into a boolean. This is also not supported by the JSON spec, which offers boolean literals true and false instead, and even JavaScript will not parse "false" the way you want (Boolean("false") === true in JavaScript).

You should change the client so that it will produce proper JSON literals for booleans, so that the default serializer can handle this properly.

Alternatively, you can switch to Newtonsoft.Json which comes with a lot additional built-in behaviors that can parse these strings into booleans. Enabling Newtonsoft.Json for ASP.NET Core 3.x+ applications is described in the migration guide.

Upvotes: 4

Related Questions