忽略ASP.NET MVC路线(Ignoring a route in ASP.NET MVC)

2019-08-17 12:56发布

我刚学与路由工作ASP.NET MVC和我试图了解IgnoreRoute方法。

我试图阻止用户访问"Content/{filename}.html" 。 我已经把这个作为我的RegisterRoutes方法中的第一个电话。 这里是我的代码:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("Content/{filename}.html");
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


    routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
                    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                    new { controller = "^.*", action = "^Index$|^About$" },
                    new[] { "UrlsAndRoutes.AditionalControllers" });
    routes.MapRoute("MyRoute2", "{controller}/{action}/{id}/{*catchall}",
                   new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                    new { controller = "^.*", action = "^Index$|^About$" },
                   new[] { "UrlsAndRoutes.Controllers" });
    routes.MapRoute("ShopSchema2", "Shop/OldAction", new { controller = "Home", action = "Index" });
    routes.MapRoute("ShopSchema", "Shop/{action}", new { controller = "Home" });
    routes.MapRoute("", "X{controller}/{action}");

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

如果我尝试访问本地主机一样的链接:53907 /内容/ Static.html,它不应该让我来显示从到目前为止我所了解的文件,但它确实显示它。

我究竟做错了什么?

Answer 1:

在MVC忽略路线会告诉MVC框架不拿起这些网址。

这意味着,它可以让底层的ASP.NET处理请求,这会很乐意告诉你一个静态文件。



Answer 2:

如果你真的想阻止访问该文件夹,为什么不能在web.config中定义的呢?

将在该文件夹中的一个web.config。

内容应该是:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <authorization>
          <!-- <allow roles="admin" /> --> //In case you want to give access to admin only.
          <deny users ="*" />
        </authorization>
    </system.web>
</configuration>


文章来源: Ignoring a route in ASP.NET MVC