问题描述
遇到一些麻烦一些路线。我不完全理解MVC路由系统让我承受的。
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!).
我想有家庭访问控制器内的意见,而无需在url家庭型态。基本上我想转成www.example.com/home/about www.example.com/about,但是我还是想preserve的www.example.com/products。
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.
推荐答案
我想你可能会寻找的东西,使code的下面笔者所称根控制器。我已经使用这个自己的一对夫妇的网站,它确实使得漂亮的网址,而不是要求您创建更多的控制器,你想,或者重复的URL结束。
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.
这路线是在Global.asax中:
This route is in Global.asax:
// Root Controller Based on: ASP.NET MVC root url’s with generic routing Posted by William on Sep 19, 2009
// http://www.wduffy.co.uk/blog/aspnet-mvc-root-urls-with-generic-routing/
routes.MapRoute(
"Root",
"{action}/{id}",
new { controller = "Root", action = "Index", id = UrlParameter.Optional },
new { IsRootAction = new IsRootActionConstraint() } // Route Constraint
);
有了这个别处定义:
With this defined elsewhere:
public class IsRootActionConstraint : IRouteConstraint
{
private Dictionary<string, Type> _controllers;
public IsRootActionConstraint()
{
_controllers = Assembly
.GetCallingAssembly()
.GetTypes()
.Where(type => type.IsSubclassOf(typeof(Controller)))
.ToDictionary(key => key.Name.Replace("Controller", ""));
}
#region IRouteConstraint Members
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string action=values["action"] as string;
// Check for controller names
return !_controllers.Keys.Contains(action);
}
#endregion
}
该RootActionContraint alows你还有其他的路线,和$ P $隐藏从任何控制器pvents的RootController行动。
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
这篇关于有一个简单的MVC路线的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!