This blog will demonstrates steps by steps web API tutorial
that explain what is WEB API and how to create a new ASP.NET Web API in ASP.NET
MVC and explain its characteristics. for more information please read my blog The Lifecycle of an ASP.NET Web API where
we discussed about the life cycle of an ASP.NET Web API message, how it travels
from Server to client.
What is Web API?
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.
Step 1: Create
an ASP.NET Web Application in Visual Studio:
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
Step 2: Add
Web API Controller
Select and right click Controllers >>Add >>
Controller
Select Web API 2 Controller – Empty - to create an
empty Web API controller
Provides API Controller Name – TaskController.cs
Here is TaskController Controller Generated Class ,
which is by default inherited by ApiController
abstract class, which provides many importance properties and methods related
to WEB API
C# : TaskController.cs
public class TaskController : ApiController
{
public TaskController()
{
}
}
Here is Model Class - Task,
which is used to transfer data from /to Web API
}
C# :
Task.cs
public class Task
{
public int TaskID
{ get; set;
}
public string Description
{ get; set;
}
Step 4: Add API Controller
Method
Add GetTaskByID API Controller
method to return the Task Model object based on input taskID
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#: 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!! Your web API is ready for use.
You can use google postman tool to test web api
For API more interactive documentation you can use the
Swagger UI and easily setup
swagger for ASP.NET Web API
1 comment:
Hire dedicated .net developers for all your web applications development, CMS customisations and migrating your existing apps to the .NET Platform seamlessly now.
Post a Comment