Search code examples
asp.net-mvcroutesignoreroute

Can I create a route that matches an already ignored route?


So, I have the following in my global.asax creating my MVC routes. They are called in the order that they appear below. What I expected to have happen was it would ignore the routes to the css folder, but then create the route to css/branding.css (which is generated at runtime from another view)

_routeCollection.IgnoreRoute("css/{*pathInfo}");

_routeCollection.MapRoute("BrandingCSS", "css/branding.css", new { controller = "Branding", action = "Css" });

Is this not possible? When I make a request to css/branding.css, I get a 404 error saying that the file does not exist. Is there a way to make this work, I'd rather it be transparent to anyone viewing source that this file is coming from anywhere but the css folder.


Solution

  • You can create and serve a custom css file by setting a RouteConstraint in your IgnoreRoute. Create the following constraint:

    public class NotBrandingCss : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            return values[parameterName].ToString().ToLowerInvariant() != "branding.css";
        }
    }
    

    Then, change your IgnoreRoute to the following:

    _routeCollection.IgnoreRoute("css/{*pathInfo}", new { pathInfo = new NotBrandingCss() });
    

    Now, a request to /css/branding.css will fail your IgnoreRoute, and will go to your BrandingCSS route, etc.