Search code examples
asp.net-mvc-routingangular2-routing

asp.net mvc6 / angular2 routing


I have asp.net mvc6 project. On client side i want to use angular2 to create single page application. It means i have two places where i can define routing. As far it's SPA, routing has to be on angular2 side, but how to deal in case when user is refreshing page? MVC returns 404.

One way would be to set Startup route in mvc6:

 routes.MapRoute(
            name: "spa-fallback",
            template: "{*url}",
            defaults: new { controller = "OAuth", action = "Index" });
        });

And then controller gives Request.Path to angular2.

However this {*url} does not recognize *.map and other static files. Also there may be scenarious where i would like to use static page like Error.html etc.

Is there any better way to deal with routing on both (server/client) side?


Solution

  • I was facing the same issues and decided to use views instead of static files.

    I have setup MVC with one Home controller that has 2 actions: Index and Login.

    The app boostraps in the index.cshtml and the login.cshtml is a simple login page.

    Routing in my startup.cs file is configured this way:

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "login",
                    template: "login",
                    defaults: new { controller = "Home", action = "Login" });
                routes.MapRoute(
                     name: "spa-fallback",
                     template: "{*url}",
                     defaults: new { controller = "Home", action = "Index" });
            });
    

    In my AppComponent I have (using Angular RC1):

    @Routes([
        { path: '/Dashboard', component: Dashboard}
    ])
    

    refreshing the page in http://localhost/Dashboard keeps me on the dashboard view, whereas http://localhost/Login redirects me to the login page, out of the angular app).

    Hope this helps