0
votes

I am building a web api for an angular front end application using ASP.Net API with the database first approach. When I test the GetPeoplez https://localhost:44333/api/people/GetPeoplez (which is supposed to be a list of people) url in postman it works, but It keep displays HTTP error 400 for the other methods of the controller

this the way I implement my controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TestApi.Collection;
using TestApi.Models;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace TestApi.Controllers
{
    [Route("api/[controller]")]
    [Controller]
    public class PeopleController : Controller
    {
        IPeopleCollection peopleCollection;
        public PeopleController(IPeopleCollection _peopleCollection)
        {
            peopleCollection = _peopleCollection;
        }

        [HttpGet]
        [Route("GetPeoplez")]
        public async Task<IActionResult> GetPeoplez()
        {
            try
            {
                var peoplez = await peopleCollection.GetPeoplez();
                if (peoplez == null)
                {
                    return NotFound();
                }

                return Ok(peoplez);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        [HttpGet]
        [Route("GetPeople")]
        public async Task<IActionResult> GetPeople(int? peopleId)
        {
            if (peopleId == null)
            {
                return BadRequest();
            }

            try
            {
                var people = await peopleCollection.GetPeople(peopleId);

                if (people == null)
                {
                    return NotFound();
                }

                return Ok(people);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        [HttpPost]
        [Route("AddPeople")]
        public async Task<IActionResult> AddPoeple([FromBody]People model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var peopleId = await peopleCollection.AddPeople(model);
                    if (peopleId > 0)
                    {
                        return Ok(peopleId);
                    }
                    else
                    {
                        return NotFound();
                    }
                }
                catch (Exception)
                {

                    return BadRequest();
                }

            }

            return BadRequest();
        }

        [HttpDelete]
        [Route("DeletePeople")]
        public async Task<IActionResult> DeletePeople(int? peopleId)
        {
            int result = 0;

            if (peopleId == null)
            {
                return BadRequest();
            }

            try
            {
                result = await peopleCollection.DeletePeople(peopleId);
                if (result == 0)
                {
                    return NotFound();
                }
                return Ok();
            }
            catch (Exception)
            {

                return BadRequest();
            }
        }


        [HttpPut]
        [Route("UpdatePeople")]
        public async Task<IActionResult> UpdatePeople([FromBody]People model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    await peopleCollection.UpdatePeople(model);

                    return Ok();
                }
                catch (Exception ex)
                {
                    if (ex.GetType().FullName ==
                             "Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException")
                    {
                        return NotFound();
                    }

                    return BadRequest();
                }
            }

            return BadRequest();
        }

    }
}

The url I use to access the api are :

  1. https://localhost:44333/api/people/GetPeople?id=x for a single people
  2. https://localhost:44333/api/people/UpdatePeople?id=x to updating an element
  3. `https://localhost:44333/api/people/AddPeople' to add a element
  4. https://localhost:44333/api/people/DeletePeople?id=x to delete an element

    and my implementation of the CRUD method is very basic

    using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TestApi.Models; using TestApi.ViewModel;

    namespace TestApi.Collection { public class PeopleCollection : IPeopleCollection { PeopleContext db;

        public PeopleCollection(PeopleContext _db)
        {
            db = _db;
        }
    
        public async Task<int> AddPeople(People people)
        {
            if (db != null)
            {
                await db.People.AddAsync(people);
                await db.SaveChangesAsync();
    
                return people.Id;
            }
    
            return 0;
        }
    
        public async Task<int> DeletePeople(int? peopleId)
        {
            int result = 0;
    
            if (db != null)
            {
                //Find the post for specific post id
                var people = await db.People.FirstOrDefaultAsync(x => x.Id == peopleId);
    
                if (people != null)
                {
                    //Delete that post
                    db.People.Remove(people);
    
                    //Commit the transaction
                    result = await db.SaveChangesAsync();
                }
                return result;
            }
    
            return result;
        }
    
    
        public async Task<List<People>> GetPeoplez()
        {
            if (db != null)
            {
                return await db.People.ToListAsync();
            }
    
            return null;
        }
    
        public async Task<People> GetPeople(int? peopleId)
        {
            return await db.People.Where(p => p.Id == peopleId).FirstOrDefaultAsync();
        }
    
    
    
    
        public async Task UpdatePeople(People people)
        {
            if (db != null)
            {
                //Delete that post
                db.People.Update(people);
    
                //Commit the transaction
                await db.SaveChangesAsync();
            }
        }
    }
    

    }

Any idea on how to overcome this error? Thanks

2
Problay because your model isn't valid. Did you check what happens when you test ModelState.IsValid?andercruzbr
As a small tip, change the method names to: GetPeople, GetPerson(int personId)Samy Sammour
Or just, GetAllAsync() and GetByIdAsync() and also the entity methods to GetPeopleAsync, and GetPersonAsync or GetByIdAsync. for a propar english name convention.Samy Sammour

2 Answers

1
votes

It's giving 400 msg means bad request error cos it's hitting some exception /error and hence going into catch block where you have specified to return bad request ....try debuggers and debug ur code

0
votes

You are sending in a X which is not an int

https://localhost:44333/api/people/GetPeople?id=x

Unless this is just an example and you are really sending a number....