Agi*_*ble 6 asp.net-mvc asp.net-mvc-routing
我试图找出如何枚举的网址Routes中RouteTable.
在我的场景中,我定义了以下路由:
routes.MapRoute
("PadCreateNote", "create", new { controller = "Pad", action = "CreateNote" });
routes.MapRoute
("PadDeleteNote", "delete", new { controller = "Pad", action = "DeleteNote" });
routes.MapRoute
("PadUserIndex", "{username}", new { controller = "Pad", action = "Index" });
Run Code Online (Sandbox Code Playgroud)
换句话说,如果我的网站是mysite.com,mysite.com/create会调用PadController.CreateNote(),而mysite.com/foobaris会调用它PadController.Index().
我还有一个强类型用户名的类:
public class Username
{
public readonly string value;
public Username(string name)
{
if (String.IsNullOrWhiteSpace(name))
{
throw new ArgumentException
("Is null or contains only whitespace.", "name");
}
//... make sure 'name' isn't a route URL off root like 'create', 'delete'
this.value = name.Trim();
}
public override string ToString()
{
return this.value;
}
}
Run Code Online (Sandbox Code Playgroud)
在构造函数中Username,我想检查以确保它name不是一个已定义的路由.例如,如果调用此方法:
var username = new Username("create");
Run Code Online (Sandbox Code Playgroud)
然后应该抛出异常.我需要更换//... make sure 'name' isn't a route URL off root什么?
通过阻止用户注册受保护的单词,这并不能完全回答您想要做的事情,但有一种方法可以约束您的路线.我们在我们的网站上有/用户名网址,我们使用了这样的约束.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" }, // Parameter defaults
new
{
controller = new FromValuesListConstraint(true, "Account", "Home", "SignIn"
//...etc
)
}
);
routes.MapRoute(
"UserNameRouting",
"{id}",
new { controller = "Profile", action = "Index", id = "" });
Run Code Online (Sandbox Code Playgroud)
您可能只需要保留一个保留字列表,或者,如果您真的想要它是自动的,您可以使用反射来获取命名空间中的控制器列表.
您可以使用此访问路径集合.这种方法的问题是它要求您明确注册您想要"受保护"的所有路由.我仍然坚持我的说法,你最好还有一个存储在别处的保留关键字列表.
System.Web.Routing.RouteCollection routeCollection = System.Web.Routing.RouteTable.Routes;
var routes = from r in routeCollection
let t = (System.Web.Routing.Route)r
where t.Url.Equals(name, StringComparison.OrdinalIgnoreCase)
select t;
bool isProtected = routes.Count() > 0;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3237 次 |
| 最近记录: |