Jorge_M_P
Jorge_M_P

Reputation: 23

Scaffold automatic WebApi Controller generation

I'm learning Web Api and I'm a bit confused.

When I create a controller for my Person class, how does it defines which method is GET, POST, DELETE? Is it the method prefix that defines it? Is it a convention set the prefix of the method to GET, POST, etc?

The generated controller is:

public class PeopleController : ApiController
{
    private PersonContext db = new PersonContext();

    // GET: api/People
    public IQueryable<Person> GetPeople()
    {
        return db.People;
    }

    // GET: api/People/5
    [ResponseType(typeof(Person))]
    public IHttpActionResult GetPerson(int id)
    {
        Person person = db.People.Find(id);

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

        return Ok(person);
    }

    // PUT: api/People/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutPerson(int id, Person person)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != person.Id)
        {
            return BadRequest();
        }

        db.Entry(person).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!PersonExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/People
    [ResponseType(typeof(Person))]
    public IHttpActionResult PostPerson(Person person)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.People.Add(person);
        db.SaveChanges();

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

    // DELETE: api/People/5
    [ResponseType(typeof(Person))]
    public IHttpActionResult DeletePerson(int id)
    {
        Person person = db.People.Find(id);
        if (person == null)
        {
            return NotFound();
        }

        db.People.Remove(person);
        db.SaveChanges();

        return Ok(person);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool PersonExists(int id)
    {
        return db.People.Count(e => e.Id == id) > 0;
    }
}

Upvotes: 1

Views: 65

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32099

No!! Its not mandatory..You can write simply Get() instead of GetPerson(), Post() instead of PostPerson() etc. Or You can also name your methods whatever names you want but you have to use Accept Verb(http verbs such as get, post, put, delete etc) attribute on the head of the methods.

Upvotes: 1

Related Questions