Fixing AngularJS + MVC Routing Issues

Currently, I’m working on a hybrid AngularJS and MVC project, one of the tasks being to get rid of the # symbol from the URL. In pure AngularJS apps, this is very easily done by following the next two steps (and easily googled):

Add the following in your angular app config: $locationProvider.html5Mode(true)

The problem arises when you are in the .NET stack and using AngularJS with MVC. The above solution will still remove the # from URL, but page refresh won’t work. Why? This happens because MVC knows nothing about AngularJS routing and by following default MVC routing, it will look for an MVC page which doesn’t exist.

The workaround is to send all MVC page requests to a single MVC view, and to do that you have to add a route to catch all requests as follows:

The base href has to set up in your _Layout page: <head> <base href=”/”> </head>

In the RouteConfig.cs, which is found in the App_Start folder, you should insert the following route:

If you have any MVC views that you need to load, you will have to add another route for them, as now with the above routing, all the other MVC views will be ignored. If you want to show a page from say the AboutController, you’ll have to add a custom route for the controller as the following: