对指定磁盘文件路由,而对其他磁盘文件不路由

在上一个例子中,有路由定义:

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.RouteExistingFiles = true;
            routes.MapRoute("DiskFile", "Content/StaticContent.html",
                new { Controller = "Account", Action = "LogOn" },
                new { customConstraint = new UserAgentConstraint("Chrome") });
            
            routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
                new { Controller = "Home", Action = "Index", id = UrlParameter.Optional },
                new { Controller="^H.*", Action="^Index$|^About$",
                httpMethod = new HttpMethodConstraint("GET")},
                new[] { "_11_3URLTestDemo.Controllers" });
        }

因为打开了routes.RouteExistingFiles = true;表明对磁盘文件都要进行路由,但是下面的路由匹配中,对磁盘文件只有一个静态匹配,也就是说只有使用Chrome浏览器对于"~/Content/StaticContent.html"的访问才会匹配到第一个定义的路由,路由到AccountController的LogOn方法上。

考虑这样的情况:在当前项目(11-3URLTestDemo)的Content文件上Add->New Item->Visual C#->Web->HTML Page,新建一个Hello.html的文件:

<html>
<head>
    <title>Hello</title>
</head>
<body>
<h2>Hello,the world.</h2>
</body>
</html>

执行程序,如果发起对"~/Content/Hello.html"的访问,资料上给出的说明是第一个路由不匹配,会匹配第二个路由,也就是将Controller匹配为Content,将Action匹配为Hello.html,由于没有这样的控制器和方法,所以会给出404错误。但实际在实验时,发现这种情况仍然访问到的是Hello.html文件,是否在MVC3中匹配后如果都没有匹配,会自动去寻找有没有该磁盘文件?

按原意,如果因为去匹配控制器和动作方法导致Hello.html无法访问,解决的方法是设定routes.IgnoreRoute绕过路由。例如:

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.RouteExistingFiles = true;
            routes.MapRoute("DiskFile", "Content/StaticContent.html",
                new { Controller = "Account", Action = "LogOn" },
                new { customConstraint = new UserAgentConstraint("Chrome") });

            routes.IgnoreRoute("Content/{filename}.html");

            routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
                new { Controller = "Home", Action = "Index", id = UrlParameter.Optional },
                new { Controller="^H.*", Action="^Index$|^About$",
                httpMethod = new HttpMethodConstraint("GET")},
                new[] { "_11_3URLTestDemo.Controllers" });
        }

-lyj

原文地址:https://www.cnblogs.com/brown-birds/p/3756685.html