Skip to content

25 Add a Web API Controller to Your Application

M. Fares edited this page Apr 6, 2018 · 8 revisions
  1. Before you start this procedure, build your application

  2. Create the model you want to expose through the API

    The purpose of creating a model is to avoid exposing navigational properties that are in the data models such as Faculties in Department model. You may create a folder where you organize your Api Models.

    Example:

public class DepartmentApiModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}
  1. Right click on the Controllers folder, then select Add > Controller

  2. Select "Web API 2 Controller With Read/Write Actions"

  3. Specify the controller name. Example: DepartmentApiController

  4. When the scaffolding is complete, a readme.txt file is displayed in Visual Studio (Not Always!)

  • Add the following namespaces to the file Global.asax
using System.Web.Http;
using System.Web.Routing; // Already there!
  • Add the following lines to the beginning of the Application_Start method in Global.asax.cs file
// Register Web API service
GlobalConfiguration.Configure(WebApiConfig.Register);
  • Add the following lines at the end of Application_Start method in Global.asax.cs file
// Serialize data to JSAON in API Controllers 
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
   .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
GlobalConfiguration.Configuration.Formatters
   .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
  1. Inspect the actions created in the API controller in the controllers folder.

    Example: /Controllers/DepartmentApiController

  2. Test your API Controller

    To test your API, you may use the browser or Postman(Preferable)

    Postman

    In your browser, go to the links:

    http://localhost:XYZ/api/DepartmentApi (Retrieve all elements in json format)

    http://localhost:XYZ/api/DepartmentApi/1 (Retrieve element 1)

    If you are using Postman, copy the address link from your browser and past it in Postman.

    Use Postman to post, put(update), and delete data. Browse youtube videos on how to do these operations with Postman.

Clone this wiki locally