ASP.NETCoreWebAPI的多个ApiControllers怎样实现?
创始人
2024-09-18 09:00:47
0

在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]替换为ProductsCustomers来访问不同的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

相关内容

热门资讯

WePoKe透视挂!红龙扑克模... WePoKe透视挂!红龙扑克模拟器,(aa poker)原来存在有挂(详细透视力荐教程),支持语音通...
透视免费(德州免费辅助神器ap... 透视免费(德州免费辅助神器app)wepokeai代打(详细辅助微扑克教程)本来真的有挂1、在德州免...
透视好友房(wepOkE)外挂... 透视好友房(wepOkE)外挂透明挂辅助代打(wepoke模拟器)一直存在有挂(详细透视攻略方法);...
wepokeai代打!德扑之星... wepokeai代打!德扑之星记分牌有什么用,(aa poker)真是真的有挂(详细辅助科技教程);...
透视数据(德州ai机器人)nz... 透视数据(德州ai机器人)nzt德州辅助(详细辅助切实教程)都是真的是有挂1、许多玩家不知道德州ai...
透视苹果版(wePoke)透视... 1、透视苹果版(wePoke)透视辅助安装(wepok软件透明挂)确实是有挂(详细透视高科技教程)(...
wpk辅助挂!德州辅助软件开发... wpk辅助挂!德州辅助软件开发定制,(wePOke)一向真的是有挂(详细辅助插件教程);wpk辅助挂...
透视辅助(微扑克ai辅助)微扑... 透视辅助(微扑克ai辅助)微扑克ai辅助器苹果版(详细辅助黑科技教程)一直存在有挂是一款可以让一直输...
透视中牌率(WePoke)外挂... 1、透视中牌率(WePoke)外挂透明挂辅助器(wepoke一定有挂)原生真的是有挂(详细透视202...
wepoke黑科技!轰趴大菠萝... wepoke黑科技!轰趴大菠萝辅助器,(wEpOke)起初存在有挂(详细透视透视教程);人气非常高,...