简单的 MVC 路线遇到问题
某些路线遇到一些问题。我并不完全理解 MVC 路由系统,所以请耐心等待。
我有两个控制器,产品和主页(还有更多控制器!)。
我希望无需在 url 中键入 Home 即可访问 Home 控制器中的视图。本质上,我想将 www.example.com/home/about 转换为 www.example.com/about,但我仍然想保留 www.example.com/products。
这是我到目前为止所拥有的。
routes.MapRoute( "Home", "{action}", new { controller = "Home" } );
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "home", action = "index", id = UrlParameter.Optional }
);
现在,根据哪个是第一个,我可以让其中一个工作,但不能同时工作。
Having some trouble with some routes. I don't fully understand the MVC routing system so bear with me.
I've got two controllers, Products and Home (with more to come!).
I want to have the views within the Home controller accessible without having to type Home in the url. Essentially I want to turn www.example.com/home/about into www.example.com/about, however I still want to preserve the www.example.com/products.
Here's what I have so far.
routes.MapRoute( "Home", "{action}", new { controller = "Home" } );
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "home", action = "index", id = UrlParameter.Optional }
);
Now depending on which one is first I can get either one or the other to work, but not both.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您可能正在寻找的是下面代码的作者称为根控制器的东西。我自己在几个网站上使用过这个,它确实可以创建漂亮的 URL,同时不需要您创建更多您想要的控制器,或者最终得到重复的 URL。
该路由位于 Global.asax 中:
在其他地方定义了此路由:
RootActionContraint 允许您仍然拥有其他路由,并防止 RootController 操作隐藏任何控制器。
您还需要创建一个名为 Root 的控制器。这不是一个完整的实现。 在此处阅读原始文章
I think what you might be looking for is something that that the author of the code below has termed a Root Controller. I have used this myself on a couple sites, and it really makes for nice URLS, while not requiring you to create more controllers that you'd like to, or end up with duplicate URLs.
This route is in Global.asax:
With this defined elsewhere:
The RootActionContraint alows you to still have other routes, and prevents the RootController actions from hiding any controllers.
You also need to create a controller called Root. This is not a complete implementation. Read the original article here
您是否尝试过:
产品仍应由默认路由处理,而第一个产品可以处理您的关于路由。
Have you tried:
Products should still be handled by the Default route, while the first one can handle your About route.