Search code examples
asp.net-mvcasp.net-web-apiasp.net-coreasp.net-mvc-routing

Routing - WebAPI and MVC in one project


I have 2 controllers. Both dealing with Bar (a child of Foo).

One of them is for MVC which returns views.

[Route("Foo/Bar")]
public class FooBarController : ControllerBase
{
    public IActionResult Index()
    {
        // ...
    }

    public IActionResult SomeAction()
    {
        // ...
    }
}

One of them is for the API, which exists under a folder of "api".

[Route("api/Foo/Bar")]
[ApiController]
public class FooBarAPIController : ControllerBase
{
    //
}

Without adding the following line to the FooBarController class, I can access the API controller (for example: /api/foo/bar/{id}), and the MVC controller (for example: /FooBar/SomeAction)

[Route("Foo/Bar")]

But when I do, routing is messed up and I get the following error trying to access /Foo/Bar/SomeAction

AmbiguousMatchException: The request matched multiple endpoints. Matches:

Controllers.MVC.FooBarController.Index

Controllers.MVC.FooBarController.SomeAction


Solution

  • I managed to get it (to be appear to be) working using the following.

    [Route("Foo/Bar")]
    [Route("Foo/Bar/[action]")]
    public class FooBarController : Controller
    {
        [HttpGet("")]
        public IActionResult Index()
        {
            return RedirectToAction("SomeAction");
        }
    
        public IActionResult SomeAction()
        {
            return View();
        }
    
    }