In this article, I am going to discuss how to Add a Controller to ASP.NET Web API Application.
Web API Controller
A controller is a class in ASP.NET Web API that handles HTTP requests. The controller's public methods are known as action methods or simply actions. When a request is received by the Web API framework, it is routed to an action. A routing table is used by the framework to select which action to do.
To create an ASP.NET Web API controller, you can follow these steps:
Create a new ASP.NET Web API project or add an API controller to an existing project. Add a new class to your project that inherits from the ApiController class.
Example
using System.Web.Http;
public class UserController : ApiController
{
// Controller logic goes here
}
Within your controller, define action methods. Based on the incoming request, the method names and their accompanying HTTP verbs (GET, POST, PUT, DELETE) define which action is performed.
Right Click on project Controller folder ->add->Controoler
Now click on the Controller and select MVC controller with Read/Write actions
The following is a simple controller class that was automatically included by Visual Studio.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebAPIStart.Controllers
{
public class UserController : Controller
{
// GET: User
public ActionResult Index()
{
return View();
}
// GET: User/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: User/Create
public ActionResult Create()
{
return View();
}
// POST: User/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: User/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: User/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: User/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: User/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
As seen in the above example, the ValuesController class is derived from ApiController and contains numerous action methods whose names correspond to HTTP verbs such as Get, Post, Put, and Delete.
Web API determines the Web API controller and action method to perform based on the incoming request URL and HTTP verb (GET/POST/PUT/PATCH/DELETE), for example. For the aforementioned Web API, the Get() function will handle HTTP GET requests, Post() method will handle HTTP POST requests, Put() method will handle HTTP PUT requests, and Delete() method will handle HTTP DELETE requests.