Asp.net mvc 将约束路由到特定文件类型

Asp.net mvc 将约束路由到特定文件类型,asp.net-mvc,asp.net-mvc-routing,url-routing,Asp.net Mvc,Asp.net Mvc Routing,Url Routing,我想写一个只适用于某些文件类型的catchall路由。现在我有 routes.MapRoute("Template", "{*path}", new {controller = "Template", action = "Default"}); 在我其他路线的底部。这对捕捉任何东西都很有效。然而,我还有一些我想忽略的遗留文件扩展名,所以目前我需要这个最后的路由来只触发.html文件 有没有路线限制我可以申请呢?我想了些办法。享受 using System; using System.Linq;

我想写一个只适用于某些文件类型的catchall路由。现在我有

routes.MapRoute("Template", "{*path}", new {controller = "Template", action = "Default"});
在我其他路线的底部。这对捕捉任何东西都很有效。然而,我还有一些我想忽略的遗留文件扩展名,所以目前我需要这个最后的路由来只触发.html文件


有没有路线限制我可以申请呢?

我想了些办法。享受

using System;
using System.Linq;
using System.Web;
using System.Web.Routing;

namespace Project.App_Start
{
    public class FileTypeConstraint : IRouteConstraint
    {
        private readonly string[] MatchingFileTypes;

        public FileTypeConstraint(string matchingFileType)
        {
            MatchingFileTypes = new[] {matchingFileType};
        }

        public FileTypeConstraint(string[] matchingFileTypes)
        {
            MatchingFileTypes = matchingFileTypes;
        }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            string path = values["path"].ToString();
            return MatchingFileTypes.Any(x => path.ToLower().EndsWith(x, StringComparison.CurrentCultureIgnoreCase));
        }
    }
}
用法:

routes.MapRoute(
    "Template", 
    "{*path}", 
    new {controller = "Template", action = "Default"}, 
    new { path = new FileTypeConstraint(new[] {"html", "htm"}) });