Search code examples
asp.net-mvcasp.net-mvc-routingurl-routing

Route constraint to specific file type


I want to write a catchall route that only applies to certain file types. Right now I have

routes.MapRoute("Template", "{*path}", new {controller = "Template", action = "Default"});

at the bottom of my other routes. This works fine for catching everything. However I have some other legacy file extensions I want to ignore so for the time being I need this final route to only trigger for .html files.

Is there a route constraint I can apply for this?


Solution

  • I figured something out. Enjoy.

    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));
            }
        }
    }
    

    Usage:

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