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

Custom Routing not working in MVC5

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

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

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,它工作正常并且它命中控制器索引方法。

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

您应该在默认 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 }
            );


        }

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

所以将它放在默认路由之上,它就会起作用。

来自MSDN的详细解释:

The order in which Route objects appear in the Routes collection is significant. Route matching is tried from the first route to the last route in the collection. When a match occurs, no more routes are evaluated. In general, add routes to the Routes property in order from the most specific route definitions to least specific ones.

Adding Routes to an MVC Application.

你可以改成

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