对于那些寻找答案或至少快速修复的人。这是我在 5 分钟后得出的结论,我当然没有想过这可能会产生任何副作用。
routes.MapNavigationRoute<HomeController>("Index", c => c.Index())
.FilterRoute(() => !WebSecurity.IsAuthenticated);
您可以在对 FilterRoute() 的调用中进行所有过滤,也可以添加更多扩展方法来节省一些字符。
我在想 .RequireRole("Adiministrators"); 依次调用 WebSecurity.RequireRoles()(或 HttpContext.Current.User.IsInRole())等。
public static NavigationRouteBuilder FilterRoute(this NavigationRouteBuilder builder, Func<bool> func)
{
var currentRoute = builder._parent;
NavigationRoutes.Filters.Add(new BootstrapAuthorizationFilter(builder, x =>
{
if (x == currentRoute)
return func();
else
return false;
}));
return builder;
}
而 BootstrapAuthorizationFilter 只是一个实现 INavigationRouteFilter 的类,它在其 ShouldRemove() 方法中调用 func()
public class BootstrapAuthorizationFilter : INavigationRouteFilter
{
private NavigationRouteBuilder builder;
private Func<NamedRoute, bool> func;
public BootstrapAuthorizationFilter(NavigationRouteBuilder builder, Func<NamedRoute, bool> func)
{
this.builder = builder;
this.func = func;
}
public bool ShouldRemove(Route navigationRoutes)
{
if (navigationRoutes is NamedRoute)
return func(navigationRoutes as NamedRoute);
return false;
}
}
显然没有什么花哨的,我不确定我是否会在生产中使用它。但我认为它足够简单并且有效(对于我测试的案例)。话虽如此,我希望新的路由功能很快就会发布:)