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

时间:2015-12-29 16:57:54

标签: asp.net-mvc routing asp.net-mvc-5.1

我有一个在MVC 5中开发的网站,我正在使用路由属性进行路由。 我使用以下代码为每个控制器设置 默认控制器 默认操作

 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并达到默认操作(索引)?该行动也应该由http://localhost:61534/analyst/Index保持可访问 谢谢你的帮助。

1 个答案:

答案 0 :(得分:5)

将空字符串作为索引操作的路由值,以便它适用于Analyst,这是您的控制器路由前缀。您可以使用第二个Route属性进行装饰,以便使用“Analyst/Index”网址将“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