Web API 2 Http Post Method

走远了吗. 提交于 2019-12-04 02:18:56

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!