This blog will demonstrates steps by steps to how to create a new ASP.NET Web API and explain its characteristics
ASP.NET Web API is a very light weight .net framework to create HTTP service and it is very easy to build restful service, which covers boarder client like mobile device, desktop and other platform.
Characteristic of Web API:
- ASP.NET Web API creates Web API on top of ASP.NET and so it can use ASP.NET request/response pipeline.
- ASP.NET Web API maps with HTTP verbs (GET, POST, PUT etc.) to Method Name.
- It supports many response Data formatter (like JSON, XML, BSON).
- It supports only HTTP protocol.
Here is 4 simple steps to create ASP.NET WEB API by using visual studio.
Step 1: Open visual studio and click New Project:
Select Visual C# a Web Asp.NET Web Application (.Net Framework) Template
Select Empty project template - it’s an empty project template for creating ASP.NET Web API project
Here is Web API Empty Project - SimpleWebAPI
Step 2: Add Web API Controller
Select Web API 2 Controller – Empty - to create an empty Web API controller
Give API Controller Name – TaskController.cs
Here is TaskController Controller Generated Class
C# Code: TaskController.cs
public class TaskController : ApiController
{
public TaskController()
{
}
}
Step 3: Add Model Class –Task.cs
C# Code: Task.cs
public class Task
{
public int TaskID { get; set; }
public string Description { get; set; }
}
Step 4: Add API Controller Method – GetTaskByID
C# Code: TaskController.cs
public class TaskController : ApiController
{
public TaskController()
{
}
[HttpGet]
public Task GetTaskByID(int taskID)
{
//@Todo Logic to get task by ID
return new Task() { TaskID = 1001, Description = "Todo Task"};
}
}
By default WebApiConfig.cs class contain web api routing settings
C# Code: WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
It’s done J !! Your web API is ready for use.
You can use google chrome postman tool to call web api
HTTP Get: http://localhost:46816/api/task?taskid=1
Response Body:
For API more interactive documentation you can use the Swagger UI and easily setup swagger for ASP.NET Web API
