我必须为这些页面开发一些页面和公共句柄(也就是别名)。
(要明白这一点:在Facebook中,您可以为自己的网页设置别名,最终网址将显示为facebook/alias
,而不是facebook/somelongpieceofsomestuff
。)
我将公共句柄存储在db表中,并确保所有句柄都是唯一的。 现在我已经为我的句柄添加了路由注册:
public override void RegisterArea(AreaRegistrationContext context)
{
// Assume, that I already have dictionary of handles and ids for them
foreach(var pair in publicHandlesDictionary)
{
var encId = SomeHelper.Encrypt(pair.Key);
context.MapRoute(pair.Value, pair.Value,
new {controller = "MyController", action="Index", id = encId});
}
}
因此,现在我可以使用地址http://example.com/alias1
代替http://example.com/MyController/Index&id=someLongEncryptedId
来访问某个页面。
这个东西很好,好的。
但是,如果我启动应用程序,然后添加新句柄怎么办?此新句柄将不会注册,因为所有路由注册都在应用程序启动时执行。基本上,我必须重新启动应用程序(IIS,VS / IIS Express,Azure,并不重要),以便再次注册所有路由,包括我的新句柄。
那么,有没有办法从控制器的动作方法添加新的路径注册(添加新句柄时)?
答案 0 :(得分:1)
你不需要在app start创建所有路线。
只需使用IRouteConstraint
来确定应该遵循别名逻辑
public class AliasConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var alias = values[parameterName];
// Assume, that I already have dictionary of handles and ids for them
var publicHandlesDictionary = SomeStaticClass.Dic;
if (publicHandlesDictionary.ContainsValue(alias))
{
//adding encId as route parameter
values["id"] = SomeHelper.Encrypt(publicHandlesDictionary.FirstOrDefault(x => x.Value == alias).Key);
return true;
}
return false;
}
}
//for all alias routes
routes.MapRoute(
name: "Alias",
url: "{*alias}",
defaults: new {controller = "MyController", action = "Index"},
constraints: new { alias = new AliasConstraint() }
);
//for all other default operations
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
通过这种方式,您可以随时更新publicHandlesDictionary
,route
将获取更改