0

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.

Anthony Shaw
  • 8,146
  • 4
  • 44
  • 62

1 Answers1

1

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.

counsellorben
  • 10,924
  • 3
  • 40
  • 38
  • interesting, thank you! This does work, but, believe it or not, when I changed the order of adding the route and the ignore route, it worked as well. I will still mark yours as an answer – Anthony Shaw Sep 28 '11 at 21:24
  • Very interesting. I had assumed that `IgnoreRoutes` were processed before `MapRoutes`, but it appears from your test that the Routes table is examined in the strict order in which items are added. Time for a deep dive into the MVC3 source. – counsellorben Sep 28 '11 at 21:28
  • yea, after re-testing this today, it did not work. I must have missed testing another of my css files and it did not work. – Anthony Shaw Sep 30 '11 at 01:51
  • What is failing? Please give some details. The example will only cause requests to /css/branding.css to fail the IgnoreRoute. Any other css requests will be ignored. – counsellorben Sep 30 '11 at 04:00
  • Sorry, I meant my solution. Your solution using an IRouteContraint works great. – Anthony Shaw Sep 30 '11 at 14:18