16.0: Http Methods

Add IHttpActionResult for all CRUD Endpoints

  1. Open ElevenNote.WebAPI -> Controllers -> NoteController

  2. Rename the Get() method to GetAll() to distinguish getting all the notes from getting just one note.

  3. See below for stubbing out the other IHttpActionResults for Get, Post, Put, and Delete

  4. CTRL . To bring in the using statement for the models. If you are using your own application, be sure to use the appropriate models from the .Models project, not the .Data assembly.

    namespace ElevenNote.WebAPI.Controllers
    {
        [Authorize]
        public class NoteController : ApiController
        {
            public IHttpActionResult GetAll()
            {
                NoteService noteService = CreateNoteService();
                var notes = noteService.GetNotes();
                return Ok(notes);
            }

            public IHttpActionResult Get(int id)
            {
                return Ok();
            }

            public IHttpActionResult Post(NoteCreate note)
            {
                return Ok();
            }

            public IHttpActionResult Put(NoteEdit note)
            {
                return Ok();
            }

            public IHttpActionResult Delete(int id)
            {
                return Ok();
            }

            private NoteService CreateNoteService()
            {
                var userId = Guid.Parse(User.Identity.GetUserId());
                var noteService = new NoteService(userId);
                return noteService;
            }
        }
    }

Get Method

Finish out the Get(int id) method:

public IHttpActionResult Get(int id)
{
    NoteService noteService = CreateNoteService();
    var note = noteService.GetNoteById(id);
    return Ok(note);
}

Post Method

Finish out the Post(NoteCreate note) method:

public IHttpActionResult Post(NoteCreate note)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var service = CreateNoteService();

    if (!service.CreateNote(note))
        return InternalServerError();

    return Ok();
}

Put Method

Finish out the Put(NoteEdit note) Method:

public IHttpActionResult Put(NoteEdit note)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var service = CreateNoteService();

    if (!service.UpdateNote(note))
        return InternalServerError();

    return Ok();
}

Delete Method

Finish out the Delete(int id) method:

public IHttpActionResult Delete(int id)
{
    var service = CreateNoteService();

    if (!service.DeleteNote(id))
        return InternalServerError();

    return Ok();
}
Git

Next, we'll look at the API docs and test the endpoints.

Last updated