自定义路由在MVC5中不起作用

时间:2015-10-13 09:28:54

标签: asp.net-mvc c#-4.0 asp.net-mvc-5 url-routing

首先,我对MVC很新,这是我的第一个项目。

我正在尝试实现自定义路由网址,如下所示:

http://mywebsite/MDT/Index/ADC00301SB

类似于...... http://mywebsite/ {控制器} / {操作} / {查询}

在我的RouteConfig.cs中,我提出以下内容

routes.MapRoute(
                name: "SearchComputer",
                url: "{controller}/{action}/{query}",
                defaults: new { controller = "MDT", action = "Index", query = UrlParameter.Optional }
            );

在我的MDTController.cs中,我有以下代码

public ActionResult Index(string query)
        {
            Utils.Debug(query);
            if (string.IsNullOrEmpty(query) == false)
            {
                //Load data and return view 
                //Remove Codes for clarification
            }

            return View();
        }

但它不起作用,如果我使用http://mywebsite/MDT/Index/ADC00301SB

,我总是在查询中得到NULL值

但是如果我使用http://mywebsite/MDT?query=ADC00301SB,它工作正常并且它会触及Controller Index方法。

您能告诉我如何正确映射路由吗?

3 个答案:

答案 0 :(得分:1)

我遇到的一个问题是将路线放在默认路线下方会导致默认路线被击中,而不是自定义路线。

所以把它放在默认路线上面就可以了。

MSDN的详细解释:

  

Route对象在Routes集合中出现的顺序非常重要。尝试从集合中的第一个路径到最后一个路径进行路径匹配。匹配发生时,不再评估路由。通常,按照从最具体的路由定义到最不具体的路由定义的顺序,将路由添加到Routes属性。

Adding Routes to an MVC Application.

答案 1 :(得分:0)

您应该在默认MapRoute之前添加MapRoute,因为RouteCollection中的顺序很重要

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

            routes.MapRoute(
               name: "SearchComputer",
               url: "{controller}/{action}/{query}",
               defaults: new { controller = "MDT", action = "Index", query = UrlParameter.Optional }
           );

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


        }

答案 2 :(得分:0)

您可以将其更改为

routes.MapRoute(
            name: "SearchComputer",
            url: "MDT/{action}/{query}",
            defaults: new { controller = "MDT", action = "Index", query = UrlParameter.Optional }
        );
相关问题