在asp.net mvc中设置索引操作默认操作控制器

时间:2018-07-25 10:10:01

标签: c# asp.net-mvc

我正在尝试使索引动作是我编写该控制器时的默认动作

  

http // mydomain / action

通话索引操作> http // mydomain / case-studies

将调用索引操作

我写网址时的问题给了我这个消息The resource cannot be found. 我写的网址http//mydomain/case-studies应该是调用索引操作,但The resource cannot be found.

这是控制器

 [RoutePrefix("case-studies")]
public class case_studiesController : Controller
{
    // GET: CaseStudies
    [Route("Index")]
    public ActionResult Index()
    {

        return View("/views/case-studies/Index.cshtml");
    }

    [Route("adaep")]
    public ActionResult adaep()
    {
        return View("/views/case-studies/pagename.cshtml");
    }
}

这是我的路线

 public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

    }
}

2 个答案:

答案 0 :(得分:2)

此答案与我合作,以将本地路由保留为默认值,并对我将每个路由从[Route(“ Index”)]更改为[Route(“”)]且具有相同路由的每个控制器都采取默认操作

      [Route("")]
    public ActionResult Index()
    {

        return View("/views/case-studies/Index.cshtml");
    }

 public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id =    UrlParameter.Optional }
    );

   }
}

那条路线就是这样做的。路线的定义是:如果{controller}为空,如果{action}为空,则使用“ Home”,如果{id}在id参数中具有值位置,则使用“ index”。对于只有控制器名称的每个网址,请求都应执行索引操作

routes.MapRoute(
   name: "Default",
   url: "{controller}/{action}/{id}",
   defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional     }

);

答案 1 :(得分:1)

这是因为您的MapRoute不正确,而您MapRoute的默认控制器为 Home :

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

将其更改为:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "case-studies", action = "Index", id = UrlParameter.Optional }
);