Question

I have an MVC4 project with elmah added. My global.asax's Application_Start() has

WebApiConfig.Register(GlobalConfiguration.Configuration); // #1
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);   // #2

#1 and #2 are as follows

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional } );
    }
    ...
}

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

The templates are identical and routing into the controllers works exactly as we want it (from a URI spec perspective). The issue is that the ignore route is added AFTER the WebAPI route is added. So what should be ignored by MVC4s routing and handled by Elmah (eg /elmah.axd/styles) is instead intercepted by WebAPI and the request fails => so I have no CSS in my elmah.axd pages. I tried flipping #1 and #2 in global.asax but that caused all WebAPI routing to fail - FAR worse than CSS not working in Elmah!

I basically need some way to instruct WebAPI's routing to ignore {resource}.axd/{*pathInfo} right as the first route - how can I do that?

Was it helpful?

Solution

This is what worked for us - moving the ignore out of the wrapper and as the first one.

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        //ignore route first
        RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        // And taken out of the call below
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

OTHER TIPS

Sounds like you need finer control of the order of the route definitions. Instead of pulling these in from the individual RouteConfig and WebApiConfig classes, you could define these directly in global.asax.cs like so:

RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "{controller}/{action}/{id}",
    defaults: new {id = RouteParameter.Optional});

RouteTable.Routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top