27

In ASP.NET Core (v 2.1.5) you can create controllers without having them inherit from Controller class (as you know). And if you do, you have to use RouteAttribute to define your routes. But, I'm interested if we can use implicit routing (and not attribute routing) along with ApiController attribute together. Example: Having this implicit routing in Startup.cs:

app.UseMvc(routeBuilder => 
{
    routeBuilder.MapRoute("api_default", "{controller}/{action}/{id?}");
});

And this Controller class

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

Will throw this exception:

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

Is there a way to avoid the exception?

Codingwiz
  • 192
  • 2
  • 14
amiry jd
  • 27,021
  • 30
  • 116
  • 215
  • It is referring to the `[Http*]` attributes – Nkosi Oct 28 '18 at 23:54
  • @Nkosi I did use `[HttpGet]`. Please see the update. The error is still there. – amiry jd Oct 28 '18 at 23:56
  • Any reason not wanting to inherit from Api/Controller? I mean, you still have to use a lot of ASP.NET Core classes anyway – Camilo Terevinto Oct 28 '18 at 23:58
  • 1
    according to docs https://learn.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.1#attribute-routing-requirement `Attribute routing becomes a requirement when using [ApiController]` – Nkosi Oct 29 '18 at 00:02

2 Answers2

42

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

According to official documentation

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.

Note: emphasis mine

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

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • 11
    But why? There seems to be absolutely no justification for this requirement. – Jez Aug 10 '22 at 15:07
0

Also use the [Route("api/VillaAPI")] in Controller Name hard.

abatishchev
  • 98,240
  • 88
  • 296
  • 433