对某些路线有些麻烦。我不完全了解MVC路由系统,所以请耐心等待。
我有两个控制器,产品和家用(还有更多!)。
我希望家庭控制器中的视图可以访问,而无需在URL中键入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 }
);
现在,根据哪个是第一个,我可以让其中一个工作,但不能同时工作。
答案 0 :(得分:1)
我认为您可能正在寻找的是下面代码的作者称之为根控制器的东西。我自己在几个网站上使用过它,它确实可以提供更好的URL,同时不需要你创建更多你想要的控制器,或者最终得到重复的URL。
此路线位于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
);
在其他地方定义:
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允许您仍然有其他路由,并阻止RootController操作隐藏任何控制器。
您还需要创建一个名为Root的控制器。这不是一个完整的实现。 Read the original article here
答案 1 :(得分:1)
你试过了吗?
routes.MapRoute(
"Home_About",
"About",
new { controller = "Home", action = "About" } );
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "home", action = "index", id = UrlParameter.Optional }
);
产品仍应由默认路线处理,而第一个可以处理您的关于路线。