HamedFathi
HamedFathi

Reputation: 3969

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?

Upvotes: 3

Views: 1501

Answers (2)

Mike Ideus
Mike Ideus

Reputation: 302

The author is wrong but the article Umang linked to has the answer for how to accomplish route inheritance, so I'm surprised he didn't mention it.

[ApiController]
[Route("api/[controller]/[action]", Name = "[controller]_[action]")]
public abstract class MyBase2Controller : ControllerBase
{
}

public class Products11Controller : MyBase2Controller
{
    [HttpGet]                      // /api/products11/list
    public IActionResult List()
    {
        return ControllerContext.MyDisplayRouteInfo();
    }

    [HttpGet("{id}")]             //    /api/products11/edit/3
    public IActionResult Edit(int id)
    {
        return ControllerContext.MyDisplayRouteInfo(id);
    }
}

Upvotes: 2

Umang
Umang

Reputation: 875

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

Upvotes: 3

Related Questions