in Web API 2 how to accept simple types as post parameter along with Route parameter
angularjs, asp.net-web-api
Solution
The [FromBody] is working a bit differently. Please, check this Parameter Binding in ASP.NET Web API. If you'd like to get the string `[FromBody] string remarks`, then your body must look like:
"Accepting this as the best"
Not a JSON. On the other hand, if the body contains the JSON, the most natural way how to consume that with ASP.NET Web API, is via the Entity/Object. So, we can create this
public class MyObject
{
public string remarks { get; set; }
}
And the Controller action should look like this:
[Route("{quoteId:long}/accept")]
public HttpResponseMessage AcceptQuote(long quoteId, MyObject myObject)
{
var remarks = myObject.remarks;
Problem
Hi after some struggle I am finally got past the angular js hurdle to pass the proper parameters to my server, but the web api 2 service fails to accept it. below is the sample code ``` [RoutePrefix("api/v2/bids")] public class BidsController : ApiController { [Route("{quoteId:long}/accept")] public HttpResponseMessage AcceptQuote(long quoteId,[FromBody] string remarks) { HttpResponseMessage response; response = Request.CreateResponse(HttpStatusCode.Accepted, quoteId); return response; } } ``` if you notice i have both the route parameter and also a post parameter of type sting. When I post using fiddler with the following: ``` POST http://127.0.0.1:81/api/v2/Bids/101/accept? HTTP/1.1 Authorization: Basic a2lyYW5AYWJjc2hpcHBlci5jb206a2lyYW5AYWJjc2hpcHBlci5jb20= Accept: application/json, text/plain, */* Content-Type: application/json;charset=utf-8 Referer: http://127.0.0.1:81/shipper/ Accept-Language: en-US Accept-Encoding: gzip, deflate User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0; EIE10;ENUSWOL) Host: 127.0.0.1:81 Content-Length: 40 DNT: 1 Connection: Keep-Alive Pragma: no-cache {"remarks":"Accepting this as the best"} ``` or use angularjs function: ``` function acceptQuote(quoteId, accept_remarks, fnSuccess, fnError) { return $resource("/api/v2/Bids/:id/accept", { quoteId: "@id"}, { "AcceptQuote": { method: "POST", isArray: false } }) .AcceptQuote({ id: quoteId }, { remarks: accept_remarks }, fnSuccess, fnError); } ``` returns the following error: ``` {"Message":"The request is invalid.","ModelState":{"remarks":["Error reading string. Unexpected token: StartObject. Path '', line 1, position 1."]}} ``` i expected that using `[FromBody]` was sufficient to pass the simple types as post parameters, any ideas to what else I am missing here.