gpt4 book ai didi

asp.net-mvc - 枚举 ASP.NET MVC RouteTable 路由 URL

转载 作者:行者123 更新时间:2023-12-04 15:15:37 26 4
gpt4 key购买 nike

我想弄清楚如何枚举 Routes 的 URL。在 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" });

换句话说,如果我的站点是 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;
}
}

Username 的构造函数中,我想检查以确保 name不是定义的路线。例如,如果这被称为:
var username = new Username("create");

然后应该抛出异常。我需要更换什么 //... make sure 'name' isn't a route URL off root和?

最佳答案

这并不能通过阻止用户注册 protected 词来完全回答您想要做什么,但是有一种方法可以限制您的路线。我们的网站中有/username url,我们使用了这样的约束。

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 = "" });

您可能只需要保留一个保留字列表,或者,如果您真的希望它是自动的,您可以使用反射来获取命名空间中的 Controller 列表。

您可以使用此访问路线集合。这种方法的问题在于它要求您显式注册您想要“保护”的所有路由。我仍然坚持我的声明,您最好将保留关键字列表存储在其他地方。
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;

关于asp.net-mvc - 枚举 ASP.NET MVC RouteTable 路由 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4442766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com