postasp.net-web-api2swaggerfrombodyattribute

Web Api 2 [FromBody] Request Body On Post is NULL


All,

First, I know similar question has been asked umpteen times. Second, I don't have 50 points (?!) to comment on any of them. Third, I cannot use "Answer" to clarify my question on those posts - I get warning I will be banned from answering any question in future.

Hence forced to ask again. I've tried all possible encodings - all 5 of them but I always get a NULL for the string Post Body for my controller below. I am using Swagger to test.

public class AmcoController : ApiController
{
    // GET: api/Amco?name=Blah
    public Amco Get(string name)
    {
        return Amco(name);
    }

    // POST: api/Amco
    public void Post([FromBody]string value)
    {
        System.Diagnostics.Debug.WriteLine("Request Body --> " + value);
    }

    // PUT: api/Amco?name=Blah
    public void Patch(string name, [FromBody]string value)
    {
    }

    // DELETE: api/Amco?name=Blah
    public void Delete(String name)
    {
    }
}

Get works fine. Not sure what's going on. Appreciate if someone can copy/paste and test and tell me. Using VS 2017


Solution

  • I don't know exactly why swagger dosen't take a single string value from body, bu you can do the following workaround:

    enter image description here

    Change your code to accept your Amco object (I think this is also the usual case for a post request).

    After this, the swagger ui should look like this and the request works fine.

    enter image description here

    Hope this helps, happy coding!