14.0: WebAPI Setup

14.0: Web API Project

In this section, we will set up the WebAPI.

  1. Right click on the solution and Add -> New Project

  2. Choose ASP.NET Web Application.

  3. Name it ElevenNote.WebApi, like the following screenshot:

    WebAPI Project

  4. In the menu(see below), select Web API.

  5. Change the Authentication to Individual User Accounts. Notice and memorize that the API option is in the same view as the Web MVC menu. It's easy to forget.

    WebAPI Settings

  6. Click OK and it will scaffold out the Web API project.

WebAPI Setup

  1. Important before running:

    • Copy the connection string from the ElevenNote.WebMvc Web.config file. This is the same we've been using throughout the app.

    • Paste it into the ElevenNote.WebAPI Web.config file in place of what is there

    • If you haven't already, you can remove the .mdf file from the connection string.

      Remove mdf

  2. Set ElevenNote.WebAPI as the startup project

  3. Right click on ElevenNote.WebAPI and choose Add > Reference

  4. Select the Data, Models, and Services projects.

  5. Open ElevenNote.Data -> IdentityModels.cs.

  6. Paste this code inside the ApplicationUser class:

             // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
         public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
         {
             // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
             var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
             // Add custom user claims here
             return userIdentity;
         }
  7. Here is a screenshot for context:

    Code

  8. Open ElevenNote.WebAPI -> App_Start -> WebApiConfig.cs

    • This handles the routing of the API routes

  9. Run the app

  10. Click on API

    API

  11. This is an automatically generated document listing your API endpoints

  12. Close the app

  13. Go to ElevenNote.WebAPI -> Models and delete the IdentityModels.cs file, this is already in the database

  14. CTRL SHIFT B to build the API. You should have a load of errors. Fix all of the errors with CTRL . to bring in the using statements. This is very similar to what you had to do when you created the MVC project. Notice in the screenshot that IdentityModels.cs has been deleted in the WebApi project.

Next, we'll test the API with Postman.

Last updated