Unknown developer
Unknown developer

Reputation: 5920

Angular 2 and MVC Routing together

I've built an Angular 2 SPA project with Visual Studio 2017 and I've got the following routing stuff code. Could someone please, explain to me what's the discrete role of each of the below routings:

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

If I delete either the first or the second route everything works the same like having both routes. So what is the use of having two routes?

Upvotes: 0

Views: 344

Answers (1)

John Pankowicz
John Pankowicz

Reputation: 4431

The first route is a standard MVC route that says if you get a request for "example.com/accounts/delete/123", call the "delete" action on the "accounts" controller and pass "123" as the value for the "id" argument.

The second route is for handling SPA (single page application) routes which happen to be sent to the server. Normally when you click on an internal link in an Angular app, the Angular router will intercept it and not send a request to the server. But if you were to copy, save and later paste that link as an URL in the browser, it will be sent to the server.

This "fall back route" tells the server that if it gets a route that does not exist on the server, to instead send back to the browser the result of the "Index" action on the "Home" controller. It does this because the SPA template uses that method to return the HTML that contains the Angular app tag. Therefore the Angular app will get re-loaded and eventually the internal link that was requested will be routed to.

Unless you added additional controllers on the server, or an additional action method to the Home controller, you only have one single action method and one single controller on the server. This is the reason that you can currently delete either route and your app still works. Except that if you deleted the second route, you would most likely get a 404 error, if you copy and paste an internal SPA link into the browser.

Upvotes: 1

Related Questions