Action methods in ASP.NET Web API are public methods defined in a controller class that handle incoming HTTP requests. Each action method corresponds to a specific HTTP verb (GET, POST, PUT, DELETE, etc.) and is responsible for processing the request, executing business logic, and returning an appropriate response to the client. Action methods are a fundamental part of the Web API framework, enabling developers to create RESTful services.

Key Characteristics of Action Methods

  • HTTP Verb Mapping: Action methods are typically decorated with attributes that specify which HTTP verb they respond to. For example, the [HttpGet] attribute indicates that the method handles GET requests.
  • Routing: Action methods are associated with specific routes defined in the routing configuration. The URL and HTTP method used in the request determine which action method is invoked.
  • Return Types: Action methods can return various types, including IHttpActionResult, which provides a standardized way to return HTTP responses, or specific data types that are automatically serialized to JSON or XML.
  • Parameter Binding: Action methods can accept parameters from the request URL, query string, or request body. ASP.NET Web API automatically binds these parameters to the method's parameters.

Creating Action Methods

Below is an example of a simple ProductsController that demonstrates various action methods for handling product-related requests:

        
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
[HttpGet]
public IEnumerable<Product> Get()
{
return products; // Return the list of products
}

// GET api/products/1
[HttpGet]
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
[HttpPost]
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
}

// PUT api/products/1
[HttpPut]
public IHttpActionResult Put(int id, [FromBody] Product product)
{
if (product == null || product.Id != id)
{
return BadRequest("Invalid data.");
}
var existingProduct = products.FirstOrDefault(p => p.Id == id);
if (existingProduct == null)
{
return NotFound(); // Return 404 if not found
}
existingProduct.Name = product.Name; // Update product details
existingProduct.Price = product.Price;
return StatusCode(HttpStatusCode.NoContent); // Return 204
}

// DELETE api/products/1
[HttpDelete]
public IHttpActionResult Delete(int id)
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound(); // Return 404 if not found
}
products.Remove(product); // Remove the product
return StatusCode(HttpStatusCode.NoContent); // Return 204
}
}

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.
  • The Put(int id, [FromBody] Product product) method handles PUT requests to update an existing product's details.
  • The Delete(int id) method handles DELETE requests to remove a product from the list.

Conclusion

Action methods are essential components of ASP.NET Web API controllers, allowing developers to define how their application responds to various HTTP requests. By understanding how to create and implement action methods, you can build robust and flexible RESTful services that cater to the needs of your clients.