15.0: API Controller
Add an API Controller
Stop the app
Right click on ElevenNote.WebApi -> Controllers and click Add -> Controller
Select Web Api 2 Controller - Empty
Name it NoteController(or whatever your controller needs to be named if this is an alternative app)
Add an
[Authorize]
attribute tag at the topInside the controller, add a helper method that creates a
NoteService
similar to our method in theElevenNote.Web
MVC projectnamespace ElevenNote.WebAPI.Controllers { [Authorize] public class NoteController : ApiController { private NoteService CreateNoteService() { var userId = Guid.Parse(User.Identity.GetUserId()); var noteService = new NoteService(userId); return noteService; } } }
CTRL .
to bring in the using statement for theNoteService
project and Microsoft.Asp.Net.IdentityThis will allow us to reuse our
NoteService
in the methods for the API project, much like we did in the MVC projectAbove the service method, write a method that uses the Service:
namespace ElevenNote.WebAPI.Controllers { [Authorize] public class NoteController : ApiController { public IHttpActionResult Get() { NoteService noteService = CreateNoteService(); var notes = noteService.GetNotes(); return Ok(notes); } private NoteService CreateNoteService() { var userId = Guid.Parse(User.Identity.GetUserId());
CTRL .
to bring in the using statement and then consider doing a
Next, we'll test getting notes in Postman.
Last updated