Using ApiControllerAttribute without using RouteAttribute
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
![amiry jd](https://i.stack.imgur.com/QQwxE.jpg?s=256&g=1)
amiry jd
My other SO-Profile: https://stackoverflow.com/users/974276/j-amiry I am a hard-working and innovative developer with near 18 years of experience mostly based on .NET (Framework & Core) technology stack. For the last few years, alongside developing some awesome applications, I was focused on some non-coding tasks such as building up development teams, team leading, tech leading, problem solving, consulting, architecting, reviewing other's code, and mentoring. As a self-motivated fast-learner experienced code-guy, who has a proactive personality to step up to new challenges, I think I'm the man who can get the job done.
Updated on July 09, 2022Comments
-
amiry jd almost 2 years
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 useRouteAttribute
to define your routes. But, I'm interested if we can use implicit routing (and not attribute routing) along withApiController
attribute together. Example: Having this implicit routing inStartup.cs
:app.UseMvc(routeBuilder => { routeBuilder.MapRoute("api_default", "{controller}/{action}/{id?}"); });
And this
Cotroller
[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?
-
Nkosi over 5 yearsIt is referring to the
[Http*]
attributes -
amiry jd over 5 years@Nkosi I did use
[HttpGet]
. Please see the update. The error is still there. -
Camilo Terevinto over 5 yearsAny reason not wanting to inherit from Api/Controller? I mean, you still have to use a lot of ASP.NET Core classes anyway
-
Nkosi over 5 yearsaccording to docs docs.microsoft.com/en-us/aspnet/core/web-api/…
Attribute routing becomes a requirement when using [ApiController]
-