Q:

Binding single value from the body of a POST with MVC

I am implementing a protocol in ASP.NET MVC, and I need to be able to bind data from a request made like this:
curl -H "Content-Type: application/json" -d 'true' http://example.com/operation/some_id

I have tried using the [FromBody] attribute on the parameter in my controller, like this:
public ActionResult Operation(string id, [FromBody] bool setSomething)

The above code does not work, as it throws an exception when MVC attempts to set setSomething to null.  If I change setSomething to a string, it always gets set to null, so I am unable to parse it to a bool in the action.
I don't have the luxury of changing 'true' to '=true' as I have read elsewhere when similar questions were asked.  The POST generated from the curl command above is set in stone.  What I need is some way of taking the value true (which is valid json, even without a key) from the body of the POST and assigning it to setSomething.  I also need to do this in a way that doesn't prevent me from assigning some_id to id, as I already have working with a custom route.
Does anyone know how this can be accomplished in MVC or Web API?
Any help is appreciated.

A:

I found a solution, but it's more of a workaround.
When the body of a POST is just true or false but nothing more, there is no key to bind this value to.  Therefore, MVC doesn't really have anything it can do other than run the value through a JSON deserializer, which succeeds without setting any parameters in the action.
In the end, I had to read the value directly from Request, as described in MVC controller : get JSON object from HTTP body?.
I ended up using similar code:
public ActionResult Operation(string id)
{
    var req = Request.InputStream;
    req.Seek(0, SeekOrigin.Begin);
    string rawBody = new StreamReader(req).ReadToEnd();

    bool setSomething = false;

    if(bool.TryParse(rawBody, out setSomething))
    {
        // Do something with 'setSomething'
        return Json(new { id = id, status = setSomething });
    }
    throw new ArgumentException(string.Format("{0} is not a valid boolean value", rawBody));
}

As you can see, I removed setSomething from the parameter list entirely, and rely on reading the raw input stream of the request in order to get the value.  This is in no way elegant, and does not make use of all the goodies we get from the MVC framework, but it works.

