Tonto
Tonto

Reputation: 3102

AmbiguousActionException: Multiple actions matched in MVC Core

I rather have a simple controller with just 2 methods like these.

public class ColorsController : Controller
{
    // GET: /<controller>/
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Index(int id)
    {
        return View();
    }
}

I also have an api with the same name in a different namespace. I tried implementing repository pattern and all of a sudden am getting AmbigousActionException. My Web api is contained in the WebUI.controllers.api namespace. Web api is :

namespace ePress.WebUI.Controllers.api
{
[Route("api/[controller]")]
public class ColorsController : Controller
{
    private IColorRepository _repository;
    public ColorsController(IColorRepository colorRepository)
    {
        _repository = colorRepository;
    }
    // GET: api/values
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(_repository.Get());
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        var color = _repository.Get(id);
        if (color != null)
            return Ok(color);
        return NotFound("Color not found");
    }
 }

This is the route configuration in the Startup class:

app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

Even changed the name of the main controller to Colors2Controller, and i still got the same error. Any help will be appreciated.

Upvotes: 2

Views: 2603

Answers (1)

Tonto
Tonto

Reputation: 3102

I had been pulling my hair for several hours on something that is quite basic. It happened that the 2 actions in my controller were all evaluating to the same. So all i had to do was to comment out one of the action methods.

public class ColorsController : Controller
{
    // GET: /<controller>/
    public IActionResult Index()
    {
        return View();
    }

    //public IActionResult Index(int id)
    //{
    //    return View();
    //}
}

It resolves now, it wasn't a problem because of the api nor the repository pattern I implemented. Hope this helps another person.

Upvotes: 1

Related Questions