MVC5 中的默认控制器和默认操作

Default controller and default action in MVC5

我有一个用 MVC 5 开发的网站,我正在使用 路由属性 进行路由。 我设置了 the default controllerthe default action 为每个控制器使用以下代码

 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
  }
 }

我有另一个带有默认操作的控制器:

[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
   }
 }

默认控制器运行良好,但是当我在未指定操作名称的情况下导航到分析控制器时,出现以下错误:

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

如何正确导航到 http://localhost:61534/analyst and reach the default action ( index) ? The action also should remain accessible by http://localhost:61534/analyst/Index 感谢您的帮助。

为索引操作提供一个空字符串作为路由值,以便它适用于 Analyst,这是您的控制器路由前缀。您可以使用第二个 Route 属性进行修饰,使其与“Analyst/Index” url 一起使用,您将在其中将“Index”传递给它。

[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
   }
}

这将适用于 /Analyst/Analyst/Index