May
11
2017

Angular2 / ASP.NET Core Client / Server Routing

I wanted to use Angular 2 in a ASP.NET Core project but I also wanted to use the ASP.NET Core routing to get to a Controller and then use the Angular 2 routing on the client. Very much like I've used to in Angular 1.x. All examples in books I have and I could find online were using only the client side routing. So this is how I resolved it. First add a route to the Startup.cs file Configure function in order to make ASP.NET Core handle Angular 2 routing

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

                routes.MapRoute(
                    name: "angular",
                    template: "{*url}",
                    defaults: new { controller = "Home", action = "Index" }
                    );
            });
A key component is the <base href='/'> tag which tells Angular what is the root of the routing URL. In the master _Layout.cshtml page I added a section right under the <head> tag:
<head>
    @RenderSection("root", false)
and one for the Angular scripts at the end of the head tag right before </head>:
@RenderSection("angular", false)
</head>
Then from any page you can start the client side routing by referencing the appropriate libraries and setting the respective <base> tag:
@section angular{

    <script src="/js/systemjs.config.min.js"></script>
    <script>
        System.import('/js/app/customer/main.min.js').catch(function (err) { console.error(err); });
    </script>
}
@section root{
    <base href="/Home/Index/">
}
Hope this helps. Have fun coding.

Month List