自定义路由在MVC5中不起作用 [英] Custom Routing not working in MVC5
问题描述
首先,我是MVC的新手,这是我有史以来的第一个项目。
First of all, I am very new to MVC and this is my first ever project.
我正在尝试实现自定义路由URL,如下所示:
I am trying to achieve the custom routing URL like the following:
http:// mywebsite / MDT / Index / ADC00301SB
类似于...
http:// mywebsite / {Controller} / {Action} / {query}
Similar to... http://mywebsite/{Controller}/{Action}/{query}
在我的RouteConfig.cs中,我放置了以下
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 }
);
在我的MDTController.cs中,我有以下代码
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();
}
但是它不起作用,如果我使用< a href = http:// mywebsite / MDT / Index / ADC00301SB rel = nofollow> http:// mywebsite / MDT / Index / ADC00301SB
But it's not working and I always get NULL value in query if I used http://mywebsite/MDT/Index/ADC00301SB
但是,如果我使用 http:// mywebsite / MDT?query = 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?
推荐答案
您应该在默认MapRoute之前添加MapRoute,因为RouteCollection中的顺序很重要
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 }
);
}
这篇关于自定义路由在MVC5中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!