In ASP.NET Web API, a controller is a class that handles incoming HTTP requests and returns responses to the client. Controllers are a fundamental part of the MVC (Model-View-Controller) architecture, where they act as intermediaries between the model (data) and the view (user interface). In the context of Web API, controllers are responsible for processing requests, performing business logic, and returning data in various formats, such as JSON or XML.

Key Responsibilities of a Controller

  • Handling Requests: Controllers receive HTTP requests from clients and determine how to respond based on the request's URL and HTTP method (GET, POST, PUT, DELETE, etc.).
  • Processing Business Logic: Controllers often contain the logic needed to interact with the model, such as retrieving data from a database or performing calculations.
  • Returning Responses: After processing the request, controllers return an appropriate response to the client, which can include data, status codes, and headers.
  • Routing: Controllers are associated with specific routes, allowing the Web API framework to direct requests to the correct controller and action method.

Creating a Controller in ASP.NET Web API

To create a controller in an ASP.NET Web API application, you typically follow these steps:

  1. Create a new class that inherits from ApiController.
  2. Define action methods within the controller to handle specific HTTP requests.
  3. Use attributes to specify the HTTP methods and routes for each action method.

Sample Code for a Controller

Below is an example of a simple ProductsController that manages a list of products:

        
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

public class ProductsController : ApiController
{
private static List<Product> products = new List<Product>
{
new Product { Id = 1, Name = "Product A", Price = 10.0M },
new Product { Id = 2, Name = "Product B", Price = 20.0M }
};

// GET api/products
public IEnumerable<Product> Get()
{
return products; // Return the list of products
}

// GET api/products/1
public IHttpActionResult Get(int id)
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound(); // Return 404 if not found
}
return Ok(product); // Return the product
}

// POST api/products
public IHttpActionResult Post([FromBody] Product product)
{
if (product == null)
{
return BadRequest("Invalid data.");
}
products.Add(product); // Add the new product
return CreatedAtRoute("DefaultApi", new { id = product.Id }, product); // Return 201
}
}

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}

Explanation of the Sample Code

In the example above:

  • The ProductsController class inherits from ApiController, which provides the necessary functionality for handling HTTP requests.
  • The Get() method handles GET requests to api/products and returns the list of products.
  • The Get(int id) method handles GET requests to api/products/{id} and returns a specific product based on the provided ID.
  • The Post() method handles POST requests to api/products and adds a new product to the list.

Conclusion

Controllers are a crucial component of ASP.NET Web API, responsible for processing incoming requests and returning appropriate responses. By defining action methods within controllers, developers can implement the business logic needed to interact with data models and provide a seamless experience for clients consuming the API. Understanding how to create and manage controllers is essential for building robust and scalable web services using ASP.NET Web API.