ASP.NET MVC 3路由:防止〜/ home访问?

时间:2012-04-04 16:07:53

标签: asp.net-mvc-3 seo asp.net-mvc-routing

我很好〜/映射到Home Index,并且〜/ Blog映射到Blog Index,但是如何防止〜/ Home映射到Home Index呢?我不希望从多个端点访问路由。

同样,我如何防止〜/ Controller和〜/ Controller / Index都可以访问其他所有“索引”操作?

好的〜/
不〜/家中 不〜/主页/索引
OK~ / AnyOtherController
没有〜/ AnyOtherController / Index

我认为该规则应该类似于阻止任何默认操作可以显式访问,并且在home的情况下也可以防止仅使用控制器访问它。

可以这样做吗?这是在过去完成的吗?例如,SO不会这样做(您可以访问herethere)并同时呈现主页;并且它们可能具有与“index”不同的默认操作名称,这可能也是可访问的路径。

3 个答案:

答案 0 :(得分:4)

您可以简单地声明不应将路由应用于与此模式匹配的网址。例如:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.Ignore("Home/{*pathInfo}");
    routes.Ignore("{controller}/Index");
}

匹配这些路线的URL将被视为裸页,当然不会存在。

答案 1 :(得分:4)

像这样实现它,以便将这些路由视为404错误但仍在我的MVC应用程序中(为了进行自定义错误视图):

    /// <summary>
    /// By not using .IgnoreRoute I avoid IIS taking over my custom error handling engine.
    /// </summary>
    internal static void RegisterRouteIgnores(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "IgnoreHome",
            "Home",
            new { controller = "Error", action = "NotFound" }
        );

        routes.MapRoute(
            "IgnoreIndex",
            "{controllerName}/Index/{*pathInfo}",
            new { controller = "Error", action = "NotFound" }
        );

这允许通过/home/{id}访问主页/索引操作,但我愿意接受。

答案 2 :(得分:0)

这就是我能够实现我的想法。

// Portal Sections
        routes.MapRoute("Home",
                        "",
                        new { controller = "Home", action = "Index" },
                        new[] { "Myapp.Portal.Controllers" });

        routes.MapRoute("About",
                        "about",
                        new { controller = "Home", action = "About" },
                        new[] { "Myapp.Portal.Controllers" });

        routes.MapRoute("Features",
                        "features",
                        new { controller = "Home", action = "Features" },
                        new[] { "Myapp.Portal.Controllers" });


        routes.MapRoute("Help",
                        "help",
                        new { controller = "Help", action = "Index" },
                        new[] { "Myapp.Portal.Controllers" });

        routes.MapRoute("Knowledgebase",
                        "help/kb",
                        new { controller = "Help", action = "Knowledgebase" },
                        new[] { "Myapp.Portal.Controllers" });

我可以访问

  • mysite.com
  • mysite.com/about
  • mysite.com/features
  • mysite.com/help
  • mysite.com/help/kb

无法访问
  • mysite.com/home/about
  • mysite.com/home/features

希望这有帮助:)