Sunday, July 27, 2014

ASP.NET MVC routing for Angular

As you know Angular is a single page application, hence there will be only one page on the server. So in MVC we just need a controller and an associated view. So why is there a need for routing in MVC.

It depends if you are supporting the evergreen browsers and using HTML5 Mode instead of Hashbang Mode for URL rewriting then URL looks as below

If you user bookmarked one of these Angular’s HTML5 mode URL and navigated to that url, the browser first makes a request to the server with the above url. ASP.NET routing engine deduces this routing as a List action in a ContactController and tries to fetches that controller. Since it is not present the server will return 404 error.

Another reason is why you don’t need the default MVC routing is there is only one controller. Instead of giving 404 error on the server, we can redirect the users to our home page or give some friendly error message which is hosted in the Angular app.

In either of the above two scenarios we need catch all the incoming requests and route it to the only action we have. This can be done by the below MVC route configuration

                new { controller = "Home", action = "Index" }

As you see I am catching all the incoming urls and routing it to the only controller and action I have. With this route configuration I truly have only one page on my server which kick starts my angular app.

No comments:

Post a Comment