Search code examples
c#asp.net-coreasp.net-web-api

Inheriting route attributes in ASP.NET Core Web API 3.1+


I am reading ASP.NET Core in Action book but I found a weird behaviour based on the explanation. In the book the author said:

To call the Start method you need to follow api/car/start

[Route("api")]
public class BaseController : Controller { }

[Route("car")]
public class CarController : BaseController
{
   [Route("start")]
   [Route("ignition")]
   [Route("/start-car")]
   public IActionResult Start()
   {
   /* method implementation*/
   }
}

But the explanation is not correct, In the testing sample, it works via car/start URL not api/car/start!

enter image description here Can anyone explain why api ignored exactly the opposite of what the author is saying?


Solution

  • Because it doesn't work that way. When you inherit, the route attribute will override the base class route attribute.

    The author believes that Route Attribute in inheritance works in the same way as a class and method.

    Source: https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1