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

相关内容

热门资讯

五分钟了解!雀神广东麻将设置胜... 广东雀神智能插件安装使用版本解析‌,五分钟了解!雀神广东麻将设置胜率(辅助挂)果真真的有挂(新版有挂...
总算了解!手机鄂州晃晃有外挂吗... 总算了解!手机鄂州晃晃有外挂吗(辅助挂)其实是真的有挂(有挂透明挂)-哔哩哔哩,支持语音通讯、好友开...
六分钟了解!来玩德州app辅助... 六分钟了解!来玩德州app辅助软件(辅助挂)透视辅助((2021已更新))(哔哩哔哩)是一款可以让一...
玩家科普!微信雀神小程序能开挂... 广东雀神辅助器最新版版本稳定性对比与推荐‌:玩家科普!微信雀神小程序能开挂(辅助挂)竟然是真的有挂(...
科普攻略!来玩德州app有挂吗... 科普攻略!来玩德州app有挂吗!原来是真的有挂((2023已更新))(哔哩哔哩)是一款可以让一直输的...
透视黑科技!山西大唐麻将怎么调... 透视黑科技!山西大唐麻将怎么调胜率(辅助挂)的确是真的有挂(有挂教程)-哔哩哔哩关于山西大唐麻将怎么...
8分钟科普!wopoker辅助... 8分钟科普!wopoker辅助v3.0(辅助挂)软件透明挂((2025已更新))(哔哩哔哩),您好,...
科技分享!雀神辅助器苹果版(辅... 科技分享!雀神辅助器苹果版(辅助挂)确实是真的有挂(有挂总结)-哔哩哔哩;雀神辅助器苹果版是一款益智...
五分钟了解!wepoke是不是... 五分钟了解!wepoke是不是有挂!竟然真的有挂((2020已更新))(哔哩哔哩);大神普及一款德州...
透视软件!湖北麻将卡五星助赢神... 透视软件!湖北麻将卡五星助赢神器(辅助挂)的确真的有挂(真的有挂)-哔哩哔哩;湖北麻将卡五星助赢神器...