AngularJS SPA and .NET MVC routing

How hard can it be to do .NET MVC routing properly along with your AngularJS single page app? -Not very hard. Here is how you can do it:

MVC routing in RouteConfig.cs

Most of the guides you find tells you how to handle the routing if you wan’t to have your SPA routes with an app/ or angular/ prefix. For the sake of having as simple URLs as possible and Search Engine Optimization (SEO) you should avoid redundant stuff in URLs.
So what you want to do is to define the MVC Default route first to catch requests for your MVC controllers. In case the request doesn’t match any of your controllers, you should have a “fallback” CatchAllRoute that will hit your AngularController or whatever you have.

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

    name: "CatchAllRoute",
    url: "{*url}",
    defaults: new { controller = "Angular", action = "Index" }

Now, having the default HomeController and Index method in it, when you navigate to /home/index, the request will hit your Default route. When you navigate to /whatever or /#!/login (or anything else that doesn’t match any of your controllers), it will hit the CatchAllRoute.

EDIT: This seems to work only with hashbanged urls. I’ll update the post when I figure out how to do this with HTML5 mode.


Leave a Reply

Your email address will not be published. Required fields are marked *