Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind a simple POST value in ASP.NET WebAPI RC?

I have a POST method on one of my API controllers that takes a single string value:

public string Post([FromBody] string foo) {
    return(fooOracle.ValidateFoo(foo) ? "success" : "failure");
}

I'm POSTing to this with the body of the post request as:

foo=123412341234

(i.e. it's a regular HTTP POST that you can initiate by submitting a browser form as well as using an HTTP client)

In the release candidate of WebAPI, this has silently stopped working - it just doesn't bind foo any more. To get the code working, I've had to replace the method with this:

public string Post(FormDataCollection form) {
    var foo = form.Get("foo");
    return(fooOracle.ValidateFoo(foo) ? "success" : "failure");
}

This works, but it's kinda messy and involves rather more plumbing to test than the previous version.

Have I missed some subtle change, or has the [FromBody] binding syntax been deprecated in favour of this rather verbose binding syntax? The attribute is still there but it's really not clear what it actually does in the RC version.

like image 957
Dylan Beattie Avatar asked Nov 13 '22 03:11

Dylan Beattie


1 Answers

It's actually there is a subtle change that it cannot handle inputs like 'foo=123412341234' but will handle '=123412341234' as the input. Can you make the client send it as later?

If not you could create a wrapper class as below and make your action expect stringwrapper as a parameter rather than String itself.

Class StringWrapper { public string Foo {get; set;} }

like image 193
dinesh ravva Avatar answered May 18 '23 01:05

dinesh ravva