我想创建一个不属于任何控制器的路由。表示如果url不包含任何控制器名称,则应将其重定向到特定操作
如何为此类路线创建约束。
例如,如果我有
等路线routes.MapRoute(
name: "user",
url: "{username}/{id}",
defaults: new { controller = "Home", action="username",id=UrlParameter.Optional },
constraints: new { isuser = new checkuserConstraint() }
);
应该约束什么,以便它不会重定向到默认home/index
路径
编辑:如果使用www.domain.com/admin/adminid
作为网址,则会返回错误,因为没有名为admin的控制器。在这种情况下,我希望它调用username
控制器的home
操作。
答案 0 :(得分:0)
例如,如果要将span
等网址映射到/admin/1
,首先需要在默认规则之前添加具有自定义约束的以下路由规则,以过滤掉不匹配的用户名。
AccountController.DoSomething(int id, string username)
您的自定义约束可能是这样的:
routes.MapRoute(
name: "myRoute",
url: "{username}/{id}",
defaults: new { controller = "Account", action = "DoSomething" },
constraints: new { username = new MyCatConstraint() }
);
// your other route rules are here
此路线符合以下操作:
public class MyCatConstraint : IRouteConstraint
{
// suppose this is your username list. In the real world a DB provider
private string[] _myUsernames = new[] { "user1", "user2", "user3" };
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
// return true if you found a match on your user'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 _myUsernames.Any(c => c == values[parameterName].ToString());
}
return false;
}
}