20 October 2016

Supporting client side AngularJS routing in ASP.NET MVC without a controller

For our AngularJS application, we have perused ASP.NET MVC/WebAPI template. It creates a scaffolding with lots of stuff which is really helpful in the beginning. As our app matured we began to realize that the additional stuff is just a hindrance. Whoever uses WebGrease today? Ditto for Bootstrap installed as a NuGet package.

So we went about tidying up: removing NuGet packages, cleaning up web.config etc. At one point, we wanted to remove HomeController since all it does is serve index.html for requested URLs

Recommendations found online concerning AngulerJS client side routing can generally be divided in two categories:

  • use a HomeController and
  • use URL rewriting

URL rewriting, while powerful, somehow also seems out of place. Not to mention that it relies on regular expressions, of which we are no experts.

Further attempts to force routes.MapRoute to route all URLs to index.html failed since ASP.NET MVC is controller oriented and apparently has to have a controller.

But then, while reading a rather thorough overview of ASP.NET routing, a method MapPageRoute popped up. Our index.html is a page, so maybe this is right. On first attempt, server failed complaining

Server Error in '/' Application.

There is no build provider registered for the extension '.html'

A (bit dirty) fix for this was to rename index.html to index.aspx

public static void RegisterRoutes(RouteCollection routes)
{
	routes.MapPageRoute(
        routeName: "CatchAll",
        routeUrl: "{*anything}",
        physicalFile: "~/app/index.aspx");
}

With this in place, we were able to get rid of HomeController.

A better solution would be to separate front end and Web API in two projects. Front end can then be hosted on whichever web server.