在ASP.NET Core Web API中,通常情况下会有多个ApiController。为了使不同的Controller之间有所区分,可以在Controller的类名上使用后缀来标记Controller的作用。若类名后缀使用“Controller”,则默认该类为ApiController。
例如:
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
// GET: api/Products
[HttpGet]
public ActionResult> Get()
{
return new string[] { "product1", "product2" };
}
}
[Route("api/[controller]")]
[ApiController]
public class CustomersController : ControllerBase
{
// GET: api/Customers
[HttpGet]
public ActionResult> Get()
{
return new string[] { "customer1", "customer2" };
}
}
在上述代码中,定义了两个ApiController:ProductsController和CustomersController。它们都使用了相同的路由路径api/[controller]
。
在路由处理程序中,根据路由路径中的[controller]
替换为Products
或Customers
来访问不同的Controller。
在请求http://localhost:port/api/Products时,将访问ProductsController
,请求http://localhost:port/api/Customers时,将访问CustomersController
。
如果需要为Controller添加一些特殊的URL前缀,则可以在Route属性中指定:
[Route("api/v1/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
// GET: api/v1/Products
[HttpGet]
public ActionResult> Get()
{
return new string[] { "product1", "product2" };
}
}
[Route("api/v1/[controller]")]
[ApiController]
public class CustomersController : ControllerBase
{
// GET: api/v1/Customers
[HttpGet]
public ActionResult> Get()
{
return new string[] { "customer1", "customer2" };
}
}
这样,请求http://localhost