我有这个默认的mapRoute:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
以及默认情况下其他一些声控器的其他mapRoutes,
现在,我想要一个特殊控制器的mapRoute来显示网址:myDomain.com/someValue,但是当我使用它时:
routes.MapRoute(
name: "categories",
url: "{sub}",
defaults: new { controller = "cat", action = "Index" }
);
所有 url.Actions ,"索引" 作为 @ Url.Action(" index&#)之类的操作34;,"登录")不起作用, 我也用过:
子= UrlParameter.Optional
和
子=""
,但他们没有用, 我该怎么办 ?
答案 0 :(得分:0)
您的categories
路由会捕获所有网址,因为它与该角色匹配。例如,您需要编写一个自定义约束类来过滤掉数据库中不匹配的sub
。
public class MyCatConstraint : IRouteConstraint
{
// suppose this is your cats list. In the real world a DB provider
private string[] _myCats = new[] { "cat1", "cat2", "cat3" };
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
// return true if you found a match on your cat's list otherwise false
// in the real world you could query from DB to match cats instead of searching from the array.
if(values.ContainsKey(parameterName))
{
return _myCats.Any(c => c == values[parameterName].ToString());
}
return false;
}
}
然后将此约束添加到您的路线。
routes.MapRoute(
name: "categories",
url: "{sub}",
defaults: new { controller = "cat", action = "Index" }
,constraints: new { sub = new MyCatConstraint() }
);
答案 1 :(得分:0)
domain.com/home
或domain.com/contact
它会到达这些控制器,否则通过类别。例如:
public class NotEqual : IRouteConstraint
{
private string[] _match = null;
public NotEqual(string[] match)
{
_match = match;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
foreach(var controllername in _match)
{
if (String.Compare(values[parameterName].ToString(), controllername, true) == 0)
return false;
}
return true;
}
}
修改后的版本:http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints
,您的路线将是:
routes.MapRoute(
name: "categories",
url: "{sub}",
defaults: new { controller = "cat", action = "Index" }
, constraints: new { sub = new NotEqual(new string[] { "Contact", "Home" }) }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
这样,无论您放置哪个与domain.com/contact
或domain.com/home
不同,都会重新路由到 cat 控制器
@Url.Action("Index","Contact")
应该产生:
/Contact