Custom Routing not working in MVC5

和自甴很熟 提交于 2019-12-12 03:24:45

问题


First of all, I am very new to MVC and this is my first ever project.

I am trying to achieve the custom routing URL like the following:

http://mywebsite/MDT/Index/ADC00301SB

Similar to... http://mywebsite/{Controller}/{Action}/{query}

In my RouteConfig.cs, I put the following

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

In My MDTController.cs, I have the following code

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

            return View();
        }

But it's not working and I always get NULL value in query if I used http://mywebsite/MDT/Index/ADC00301SB

But if I used http://mywebsite/MDT?query=ADC00301SB, it's working fine and it hits the Controller Index method.

Could you please let me know how I could map the routing correctly?


回答1:


You should add your MapRoute before default MapRoute, because order in RouteCollection is important

 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:


One issue that I have encountered is that placing your route below the default route will cause the default to be hit, not your custom route.

So place it above the default route and it will work.

A detailed explanation from 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.




回答3:


You can change it to

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


来源:https://stackoverflow.com/questions/33099003/custom-routing-not-working-in-mvc5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!