2012-04-04 107 views
7

我很喜欢〜/映射到首页索引,并〜/博客映射到博客索引,但如何防止〜/ Home映射到首页索引以及?我不希望路由可以从多个端点访问。ASP.NET MVC 3路由:防止〜/ home访问?

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

OK〜/
NO〜/主页
NO〜/首页/指数
OK〜/ AnyOtherController
NO〜/ AnyOtherController /索引

我猜的规则应该像防止任何默认动作可以明确地访问,而在家庭情况下也可以防止只有控制器才能访问动作。

可以这样做吗?过去是否已完成?举例来说,它不会这样做(您可以访问herethere)并且都呈现主页;并且它们可能与“index”有不同的默认操作名称,这可能也是可访问的路由。

+0

这是非常相似的问题我问了一天:http://stackoverflow.com/questions/9974402/301-redirect-original-url-request-to-routed-url。我不是说它是重复的,因为我认为它有些不同,但我也有兴趣知道这个答案。 – Curt 2012-04-04 16:11:35

+0

我很好奇你为什么不希望从多个端点访问路由。 – 2012-04-04 16:14:29

+0

也许使用nuget中的'AttributeRouting'软件包,以便您可以明确定义您的所有路线...... – dotjoe 2012-04-04 16:18:47

回答

4

实现像这样为了使这些路线是我的MVC应用程序内(为了使自定义错误,可以查看到发生)视为404错误,但仍:

/// <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},但我愿意忍受。

+0

感谢您发布您最终使用的内容。 – 2012-04-06 17:34:22

4

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

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

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

+1

他肯定不想忽略** Index **之外的所有其他** Home **操作,所以第一个必须更改为“Home”。 – 2012-04-04 17:38:03

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

希望这有助于:)