public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Add this line to register Attribute-Routing
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
// Route: GET /api/products/3
public IHttpActionResult GetProduct(int id)
{
return Ok("Product " + id);
}
// Route: GET /api/products
public IHttpActionResult GetAllProducts()
{
return Ok("All Products");
}
// Route: POST /api/products { id: 3 }
public IHttpActionResult PostProduct(ProductModel model)
{
return Ok("Create Product " + model.Id);
}
// Route: PUT /api/products/3 { id: 3 }
public IHttpActionResult PutProduct(ProductModel model)
{
return Ok("Update Product " + model.Id);
}
// Route: DELETE /api/products/3
public IHttpActionResult DeleteProduct(int id)
{
return Ok("Delete Product " + id);
}
// Route: GET /api/products/customEndPoint?id=3
[HttpGet]
[Route("customGetEndpoint")]
public IHttpActionResult CustomGetEndpoint(int id)
{
return Ok("Custom Get " + id);
}
// Route: POST /api/products/customEndPoint { id: 3 }
[HttpPost]
[Route("customPostEndpoint")]
public IHttpActionResult CustomPostEndpoint(ProductModel model)
{
return Ok("Custom Post " + model.Id);
}
}
public class ProductModel
{
public int Id { get; set; }
}