-
Notifications
You must be signed in to change notification settings - Fork 0
25 Add a Web API Controller to Your Application
-
Before you start this procedure, build your application
-
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; }
}-
Right click on the Controllers folder, then select Add > Controller
-
Select "Web API 2 Controller With Read/Write Actions"
-
Specify the controller name. Example: DepartmentApiController
-
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);-
Inspect the actions created in the API controller in the controllers folder.
Example: /Controllers/DepartmentApiController
-
Test your API Controller
To test your API, you may use the browser or Postman(Preferable)
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.