从MVC 5中的URL中删除控制器“Home”(Remove controller 'Home' from URL in MVC 5)

编程入门 行业动态 更新时间:2024-10-27 21:11:47
从MVC 5中的URL中删除控制器“Home”(Remove controller 'Home' from URL in MVC 5)

我需要从项目的URL中删除控制器“Home”,现在它看起来像这样:example.com/Home/contact,我希望它看起来像这样:example.com/contact(也用于其他部分作为服务) ,我们的团队,画廊等)

我尝试删除RouteConfig.cs代码中“{action} / {id}”之前出现的“{controller}”,如下所示:

namespace myproject { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", "{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }

并且控制器“Home”从URL中消失,但以下指向登录和管理的链接不起作用:

@Html.ActionLink("Login here", "Login", "Account") @Html.ActionLink("Manage website", "Index", "Manage")

如何在不在URL中显示控制器“Home”的情况下使这些链接工作?

I need to remove the controller 'Home' from the URL of my project, now it looks like this: example.com/Home/contact and i want it to look like this: example.com/contact (also for other sections as services, our-team, gallery, etc.)

I tried to remove the '{controller}' that appears before '{action}/{id}' in RouteConfig.cs code, like this:

namespace myproject { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", "{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }

And the controller 'Home' disappears from the URL, but the following links to login and Manage do not work:

@Html.ActionLink("Login here", "Login", "Account") @Html.ActionLink("Manage website", "Index", "Manage")

How could i make those links work without displaying the controller 'Home' in the URL?

最满意答案

您需要将以下内容添加到RouteConfig.cs中

routes.MapRoute( name: "contact", url: "contact", defaults: new { controller = "Home", action = "Contact" } );

确保“默认”路由映射是最后一个。

You'll need to add the following to your RouteConfig.cs

routes.MapRoute( name: "contact", url: "contact", defaults: new { controller = "Home", action = "Contact" } );

Make sure that the "Default" route mapping is the last one.

更多推荐

本文发布于:2023-04-27 11:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326166.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   URL   MVC   controller   Remove

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!