如何在 ASP.NET 中添加 API 个端点?

How do I add API Endpoints in ASP.NET?

我想在 ASP.NET 中注册 API 端点,只需在 ApiController 中添加一些方法即可。那里的新方法意味着新的 API.

在下面的随机示例中:

public class ProductController : ApiController

需要为以下端点提供服务:

/
/price
/price/discount

这里的问题是所有端点都对 / 发出 GET 请求,并导致与 / 相同的输出。

Reference URL and Service Contract

您可以在要使用自定义路由的方法上放置路由注释。

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()
    {
        ...
    }

}