如何从URL中使用MVC狂胜卸下控制器名称 [英] how to remove the controller name from the url using rout in MVC
问题描述
如何在MVC 5.删除URL控制器名称我尝试添加在route.config路线
How to remove the controller name from the URL in MVC 5. I tried to add the route in the route.config
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 }
);
routes.MapRoute(
name: "Special",
url: "action/{id}",
defaults: new { controller = "Home", action = "LandingIndex", id = UrlParameter.Optional }
);
}
}
当我试图访问一个由 HTTP的网址://本地主机:24220 / LandingIndex 的它会提示404错误。
如何解决这个问题。
When I tried to a access the URL by http://localhost:24220/LandingIndex it will prompt 404 error. how to resolve this issue
推荐答案
您可以尝试先放置更专业化的路线反向路由定义。另外你可能不想硬code中的操作名称为操作
而是使用 {行动}
占位符:
You could try inverting the routes definition by placing the more specialized route first. Also you probably didn't want to hardcode the action name as action
but rather use the {action}
placeholder:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Special",
url: "{action}",
defaults: new { controller = "Home", action = "LandingIndex" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
现在,当您导航到 / LandingIndex
,在首页的
控制器应被调用。 LanginIndex
行动
Now when you navigate to /LandingIndex
, the LanginIndex
action on the Home
controller should be invoked.
另请注意,我已删除从第一路由的可选的 {ID}
占位符。这其中的原因是因为如果它是present,路由引擎将不会使用第二条路线。例如,如果你尝试加载 /首页/指数
将查找在首页
行动首页
控制器,并将其传递首页
为 ID
。如果你想有这样的 {ID}
令牌,你将需要使用约束带你的第二个更一般的路由定义为diambiguate。例如,如果你标识符总是整数或遵循某种模式,你可以写一个正则表达式约束将匹配他们。
Also notice that I have removed the optional {id}
placeholder from the first route. The reason for that is because if it were present, the routing engine would never use the second route. For example if you try to load /Home/Index
it will look for a Home
action on the Home
controller and passing it Index
as id
. If you want to have this {id}
token you will need to use a constraint to diambiguate with your second more general route definition. For example if your identifiers are always integers or follow some pattern, you could write a regex constraint that will match them.
这篇关于如何从URL中使用MVC狂胜卸下控制器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!