【问题标题】:Prevent access to route with "/Index"使用“/Index”阻止访问路由
【发布时间】:2015-09-10 22:02:45
【问题描述】:

在 .NET MVC 路由中,有没有办法让我在显式键入索引操作时阻止对它的访问,即我希望它返回 404,就好像该操作无效一样?

我想实现:

www.example.com /Index => 404 错误代码

www.example.com => “Root”,应该在默认控制器上运行 Index 操作。

就像 StackOverflow 上的类似,/Index 给我 404,这也是我想要模拟的。

现在,//Index 都给了我一个有效的页面 - 起始页面。

现在的默认路由:

routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

【问题讨论】:

  • 删除与该 URL 匹配的路由。
  • @SLaks 我应该如何重写默认路由?
  • 我刚刚启动了一个新的 MVC 项目,转到 /Index 并得到一个 404...你改变了什么?您是否转到:/Home/Index ?

标签: c# .net asp.net-mvc routes


【解决方案1】:

假设您的意思是/Home/Index 而不是/Index,您只需将IgnoreRoute 添加到您的配置中。

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.IgnoreRoute("Home/Index");
        routes.IgnoreRoute("Home");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

【讨论】:

    【解决方案2】:

    我通过将默认路由 (Root) 的 URL 更改为空来解决此问题。

    在 ASP.NET Core 1.1.1 中

    app.UseMvc(routes =>
    {
       routes.MapRoute("Home_Root", "", new { controller = "Home", action = "Index" });
    });
    

    【讨论】:

      猜你喜欢
      • 2022-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2017-10-08
      • 2020-01-31
      • 1970-01-01
      相关资源
      最近更新 更多