C#

How i will return status code & message depend on condition in API?

[HttpGet(\"{id:int}\")] public ActionResult GetVilla(int id) { if (id == 0) { return BadRequest(); //return 400 } var villa = VillaStore.villasLi...

J
Joynal Abedin
3
        [HttpGet(\"{id:int}\")]
        public ActionResult  GetVilla(int id)
        {

            if (id == 0) {
                return BadRequest(); //return 400
            }

            var villa = VillaStore.villasList.FirstOrDefault(u => u.Id == id);

            if (villa == null) {
                return NotFound(); //return 404 not found
            }

            return Ok(villa); //return 200 success
        }

Here when user try to get data entering id. If user enter id zero(0) then it's called BadRequest which return 400. If user enter any id which is not exist in list then user will get 404 code which means data not found. If data exist then user will get 200 code with success message.

J

Written by Joynal Abedin

Passionate about technology, code, and sharing knowledge.

0 Comments

Leave a Comment