在不使用 RouteAttribute 的情况下使用 ApiControllerAttribute

Using ApiControllerAttribute without using RouteAttribute

在 ASP.NET Core (v 2.1.5) 中,您可以创建控制器,而无需让它们继承自 Controller class(如您所知)。如果这样做,则必须使用 RouteAttribute 来定义路线。但是,如果我们可以将隐式路由(而不是属性路由)与 ApiController 属性一起使用,我很感兴趣。示例:在 Startup.cs:

中具有此隐式路由
app.UseMvc(routeBuilder => 
{
    routeBuilder.MapRoute("api_default", "{controller}/{action}/{id?}");
});

还有这个Cotroller

[ApiController]
public class ValuesController 
{
    [HttpGet] 
    public string Get(int id) => id.ToString();
}

会抛出这个异常:

InvalidOperationException: Action 'TestApi.Controllers.ValuesController.Get' does not have an attribute route. Action methods on controllers annotated with ApiControllerAttribute must be attribute routed.

有没有办法避免异常?

But, I'm interested if we can use implicit routing (and not attribute routing) along with ApiController attribute together.

根据官方文档

Attribute routing becomes a requirement. For example:

[Route("api/[controller]")]
[ApiController]
public class ValuesController 

Actions are inaccessible via conventional routes defined in UseMvc or by UseMvcWithDefaultRoute in Startup.Configure.

注:强调我的

引用Build web APIs with ASP.NET Core: Attribute routing requirement