Testing JSON Serialization with cURL

I've been working on a REST API in ASP.NET Web API 2. (It's a wrapper for server-side SOAP APIs, but that's neither here nor there for this.)

I had a strange problem trying to generate the JWT. The POST URL would require the parameters to be formatted as clientid, clientsecret and granttype rather than the nominal client_id, client_secret and grant_type.

Snake case was set in the app (I did this after the individual JsonProperty options were not working.

For reference, in WebApiConfig.cs

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() };  

This is the spot to place any global serializer settings, such as returning string values from enums.

Anyway, after no success with any of this (responses were all snake_case, but testing with cURL or $.ajax was not working.

Fixing the jQuery AJAX call was easy: wrap the data with JSON.stringify.

  method: "POST",
  contentType: "application/json",
  dataType: "json",
  url: "/your/auth/url",
  data: JSON.stringify({
    username: "me@example.com",
    password: "soopersekritpassword",
    client_id: "[client id]",
    client_secret: "[client secret token]",
    grant_type: "password"
}).done(function(response) { 

Turns our I was the problem with cURL. By default, cURL uses form data to post data (e.g. username=me@example.com&password=soopersekritpassword...) but we need it to pass it as JSON.

The way to do this is to pass a header value with the required content type and the data as stringified JSON.

So the call becomes:

curl -X POST -H "Content-Type: application/json" -d '{"username":"me@example.com","password":"soopersekritpassword","grant_type":"password","client_id":"[client id]","client_secret":"[client secret token]"}' http://path/to/your/auth  

And now the parameter bindings work as expected.


Matt Redmond

Musician, composer, actor, engineer, pirate.

Adelaide, Australia