markneustadt.com

WebAPI – Accepting both form data and query string parameters

Recently, I had to write a WebAPI method in C# that would be an HTTP POST.  Basically, I wanted to hit

http://localhost:99/api-demo/samplemethod/myIdString

and pass a bunch of data in the body of the request. Simple, no?

In our project, we make heavy use of the Route attribute to decouple the method name from the URL.  My method looked okay.

    [RoutePrefix("api-demo")]
    [SetUser]
    public class DemoController : ApiController
    {
        [HttpPost]
        [Route("samplemethod")]
        public IHttpActionResult Sample([FromBody] string requestBody, string id)
        {
            return Ok(String.Format("Request with ID {0} body has a length of {1}", id, requestBody.Length));
        }
    }

This sample code is clearly very simple.  I have decoupled the controller to api-demo and the method to samplemethod. It appears like everything would work as expected, however when I would test it via POSTMAN, I get the following response:

{
  "$id": "1",
  "Message": "No HTTP resource was found that matches the request URI 'http://localhost:99/api-demo/samplemethod/1134630'.",
  "MessageDetail": "No type was found that matches the controller named 'api-demo'."
}

What the heck? My method has the request body right in there along with the id. Looking at the RouteConfig certainly makes it look like the ID would be expected.

But wait… that Route attribute… I bet that’s my culprit. A quick update to that….

        [Route("samplemethod/{id}")]

And…

postbodyandquerystring

 

 

 

 

SUCCESS!

Here’s the full body of the code.

    [RoutePrefix("api-demo")]
    [SetUser]
    public class DemoController : ApiController
    {
        [HttpPost]
        [Route("samplemethod/{id}")]
        public IHttpActionResult Sample([FromBody] string requestBody, string id)
        {
            return Ok(String.Format("Request with ID {0} body has a length of {1}", id, requestBody.Length));
        }
    }

Leave a Reply

Scroll To Top