Monday, June 15, 2015

MVC 6 Routing for Angular Application

If you are working on a single page application, then you will have only one view in your application. From this view you load up the angular application (or other frameworks) and then fetch the data through ajax. Once loading this single MVC view, we utilize angular routing to load different angular views while user is navigating from one page to another.

In some cases we need to provide an ability for the user to book mark a particular angular view and return directly to that without going to start. This would get tricky as when the application loads, MVC routing thinks that user is trying to reach to an MVC controller/view and returns 404 as it could not find it.

For example, user bookmarked, http://domain.com/vehicle/details. This url should load the default MVC view and then using Angular routing loads the vehicle details. But when we pass this url to MVC, MVC with its default routing tries to fetch the VehicleController and throws 404 error as it could not find it. To avoid this we need to define a catch all route in MVC which returns the default view. Here is the catch all routing:

    routes.MapRoute(
        name: "default",
        template: "{*url}",
        defaults: new { controller = "Home", action = "Index" });

With the above routing we route all urls to our one MVC view. But we should be able to pass our WebAPI controllers thought this routing. Unlike MVC 5 and earlier versions, WebAPI is integrated with MVC and uses the same routing. Hence to differentiate these two I am using a prefix of “api” in the url. I defined an additional route called webapi which defines routing for all my webapi requests.

    routes.MapRoute(
        name: "webapi",
        template: "api/{controller}/{action}/{id?}",
        defaults: new { controller = "Home", action = "details" });

With above two route definitions I can provide an ability for the user to directly go to any particular angular view and also get the data from the server using Web API.

Here is the full routing definition for an MVC 6 Angular single page application:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "webapi",
        template: "api/{controller}/{action}/{id?}",
        defaults: new { controller = "Home", action = "Index" });

    routes.MapRoute(
        name: "default",
        template: "{*url}",
        defaults: new { controller = "Home", action = "Index" });

});

2 comments:

  1. Thanks for this post. I'm new to MVC and had problem figuring this out. Your post saved my some headaches

    ReplyDelete
  2. This post is really useful for the beginners like me

    ReplyDelete