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

相关内容

热门资讯

辅助开挂!湖北卡五星教程辅助,... 辅助开挂!湖北卡五星教程辅助,aapoker发牌逻辑(透视)开挂辅助安装(有挂秘籍);超受欢迎的湖北...
开挂辅助!蛮王大厅透视辅助,w... 开挂辅助!蛮王大厅透视辅助,wpk俱乐部辅助器(透视)开挂辅助安装(有挂讲解);是一款可以让一直输的...
开挂辅助!九天大厅辅助器,ne... 开挂辅助!九天大厅辅助器,newpoker怎么安装脚本(透视)开挂辅助脚本(有挂方针);一、九天大厅...
开挂辅助!wepoker免费透... 开挂辅助!wepoker免费透视脚本,哈糖大菠萝能开挂吗(透视)开挂辅助软件(有挂分享);1、不需要...
辅助开挂!欢聚水鱼辅助,wep... 辅助开挂!欢聚水鱼辅助,wepoker透视底牌脚本(透视)开挂辅助软件(有挂解惑);是一款可以让一直...
开挂辅助!情怀七喜游戏辅助,悦... 开挂辅助!情怀七喜游戏辅助,悦扑克脚本(透视)开挂辅助软件(确实有挂);最新版2026是一款经典耐玩...
辅助开挂!哥哥打大a辅助辅助,... 辅助开挂!哥哥打大a辅助辅助,佛手在线大菠萝智能辅助器(透视)开挂辅助平台(有挂存在);哥哥打大a辅...
开挂辅助!蛮王大厅房卡辅助,w... 开挂辅助!蛮王大厅房卡辅助,we-poker辅助器(透视)开挂辅助神器(有挂透明挂);1、超多福利:...
开挂辅助!潮友会鱼虾蟹破解,w... 开挂辅助!潮友会鱼虾蟹破解,we-poker辅助(透视)开挂辅助下载(确实有挂);详细潮友会鱼虾蟹破...
辅助开挂!微信牵手跑有没有挂,... 辅助开挂!微信牵手跑有没有挂,wpk透视辅助靠谱吗(透视)开挂辅助安装(发现有挂);最新版2026是...