In ASP.NET MVC 5, Web API methods are typically part of a controller that handles HTTP requests like GET, POST, PUT, DELETE, etc. Below is an overview of the most common Web API methods and their associated HTTP verbs:
1. GET
The GET
method is used to retrieve data from the server. In Web API, this method retrieves a collection of resources or a single resource.
{
// GET api/products
public IEnumerable
{
return productService.GetAllProducts();
}
// GET api/products/{id}
public IHttpActionResult Get(int id)
{
var product = productService.GetProductById(id);
if (product == null)
{
return NotFound();
// Return a 404 if not found
}
return Ok(product);
// Return a 200 with the product data
}
}
2. POST
The POST
method is used to send data to the server to create a new resource.
{
// POST api/products
public IHttpActionResult Post([FromBody] Product product)
{
if (product == null)
{
return BadRequest("Invalid product data");
}
productService.AddProduct(product);
return CreatedAtRoute("DefaultApi", new { id = product.Id }, product);
// 201 Created
}
}
3. PUT
The PUT
method is used to update an existing resource on the server.
{
// PUT api/products/{id}
public IHttpActionResult Put(int id, [FromBody] Product product)
{
if (product == null || product.Id != id)
{
return BadRequest("Product data is invalid.");
}
var existingProduct = productService.GetProductById(id);
if (existingProduct == null)
{
return NotFound(); // 404 if the product does not exist
}
productService.UpdateProduct(product);
return StatusCode(HttpStatusCode.NoContent);
// 204 No Content
}
}
4. DELETE
The DELETE
method is used to delete a resource from the server.
{
// DELETE api/products/{id}
public IHttpActionResult Delete(int id)
{
var product = productService.GetProductById(id);
if (product == null)
{
return NotFound();
// 404 Not Found
}
productService.DeleteProduct(id);
return StatusCode(HttpStatusCode.NoContent);
// 204 No Content
}
}
5. PATCH (Optional)
The PATCH
method is used to apply partial updates to a resource.
{
// PATCH api/products/{id}
public IHttpActionResult Patch(int id, [FromBody] JsonPatchDocument
{
var product = productService.GetProductById(id);
if (product == null)
{
return NotFound();
}
patchDocument.ApplyTo(product);
productService.UpdateProduct(product);
return Ok(product);
}
}
Key Considerations:
- Use
IHttpActionResult
as the return type for better flexibility in returning various HTTP status codes (OK, NotFound, BadRequest, etc.). - The
[FromBody]
attribute indicates that the data will be sent in the body of the request, typically in JSON format. - These methods follow RESTful conventions, where each method corresponds to a specific HTTP verb.
By implementing these Web API methods, you can build a full CRUD (Create, Read, Update, Delete) API for your application.