C# – Web API 2 Http Post Method

asp.net-web-api2c

I am disgusted not have found a solution to this problem.

I started creating a new api using Web API 2 and just cannot get the POST and PUT to work. The Get all and Get single item works perfectly fine.

There are no related articles anywhere, and those that i've found relates only to Gets and Web API, but not Web API 2.

Any assistance would do please.

    // POST: api/checkOuts
    [HttpPost]
    [ResponseType(typeof(checkOut))]
    [ApiExplorerSettings(IgnoreApi = true)]
    public async Task<IHttpActionResult> PostcheckOut(checkOut co)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.checkOuts.Add(checkOut);

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (checkOutExists(checkOut.id))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtRoute("DefaultApi", new { id = checkOut.id }, checkOut);
    }

So basically, I'm just attempting to get a debug into the method.

Was especially disappointed in this link as it covered almost everything, but ai. http://www.asp.net/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing

Regards

Best Answer

This is a working code

        // POST api/values
        [HttpPost]
        [ResponseType(typeof(CheckOut))]
        public async Task<IHttpActionResult> Post([FromBody] CheckOut checkOut)
        {
            if (checkOut == null)
            {
                return BadRequest("Invalid passed data");
            }

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.checkOuts.Add(checkOut);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (checkOutExists(checkOut.id))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("DefaultApi", new { id = checkOut.Id }, checkOut);
        }

I've declared CheckOut class to be like this :

public class CheckOut
{
   public int Id { get; set; }
   public string Property2 { get; set; }
}

The Key things here are :

1- You need to add [FromBody] to your Api method. 2- I've tested it using Fiddler, i- by choosing POST action. ii- content-type: application/json. iii- passing {"Id":1,"Property2":"Anything"} in the message body.

Hope that helps.