Route restriction for a specific file type

I want to write a complete route that only applies to certain types of files. Right now I have

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

      

at the bottom of my other routes. This works great to catch everything. However, I have some other legacy file extensions that I want to ignore, so for now I need this last route to only run .html files.

Is there a route restriction that I can apply for this?

+3


source to share


1 answer


I understood something. 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));
        }
    }
}

      



Using:

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

      

+3


source







All Articles