4
votes

I have a website developed in MVC 5, I'm using route attributes for routing. I've set the default controller and the default action for each controller using the following code

 public class CompanyController : MainController
 {
  [Route("~/", Name = "default")]
  [Route("Company/Index")]
  public ActionResult Index(string filter = null)
   {
     //My code here
   }

  [Route("Company/Edit")]
  public ActionResult Edit(int id)
  {
    //My code here
  }
 }

I've another controller with a default action :

[RoutePrefix("Analyst")]
[Route("{action=Index}")]
  public class AnalystController : MainController
 {
    [Route("Analyst/Index")]
    public ActionResult Index(string filter = null)
    {
      //My code here
    }

   [Route("Analyst/Edit")]
   public ActionResult Edit(int id)
   {
    //My code here
   }
 }

The default controller worked perfectly, but when I navigate to the analyst controller without specifying the name of the action I get the following error:

Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.

The request has found the following matching controller types: 
SurveyWebsite.Controllers.AnalystController
SurveyWebsite.Controllers.CompanyController

How can I correct navigate to http://localhost:61534/analyst and reach the default action ( index) ? The action also should remain accessible by http://localhost:61534/analyst/Index Thanks for your help.

1

1 Answers

5
votes

Give an empty string as the route value for index action so that it works for Analyst, which is your controller route prefix. You can decorate with a second Route attribute for it to work with "Analyst/Index" url where you will pass "Index" to it.

[RoutePrefix("Analyst")]
public class AnalystController : MainController
{
    [Route("")]
    [Route("Index")]
    public ActionResult Index(string filter = null)
    {
      //My code here
    }

   [Route("Edit/{id}")]
   public ActionResult Edit(int id)
   {
    //My code here
   }
}

This will work for both /Analyst and /Analyst/Index