加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – MVC5中的默认控制器和默认操作

发布时间:2020-12-16 06:39:38 所属栏目:asp.Net 来源:网络整理
导读:我有一个在MVC 5中开发的网站,我正在使用路由属性进行路由. 我使用以下代码为每个控制器设置了默认控制器和默认操作 public class CompanyController : MainController { [Route("~/",Name = "default")] [Route("Company/Index")] public ActionResult Inde
我有一个在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之前保持可用
谢谢你的帮助.

解决方法

给出一个空字符串作为索引操作的路由值,以便它适用于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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读