asp.net-web-apiendpoints

How do I add API Endpoints in ASP.NET?


I would like to register API Endpoints in ASP.NET by just adding few methods in ApiController. A new method there means a new API.

In a random example below:

public class ProductController : ApiController

needs to serve the following Endpoints:

/
/price
/price/discount

Problem here is all endpoints are having a GET request to /, and result in same output as /.

Reference URL and Service Contract


Solution

  • You can place Route annotation at method for which you want to use custom route.

    public class CustomersController : ApiController
    {
        // this will be called on GET /Customers or api/Customers can't remember what default
        //config is
        public List<Customer> GetCustomers()
        {
            ...
        }
    
        // this will be called on GET /My/Route/Customers
        [HttpGet, Route("My/Route/Customers)]
        public List<Customer> GetCustomersFromMyRoute()
        {
            ...
        }
    
    }