Angular 2 - Routing with ASP.NET MVC

I am trying to use ASP.NET MVC (not the kernel) with AngularJS 2 and some routing problems.

First in RouteConfig.cs, I defined the following routes

routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); // when the user types in a link handled by client side routing to the address bar // or refreshes the page, that triggers the server routing. The server should pass // that onto the client, so Angular can handle the route routes.MapRoute( name: "spa-fallback", url: "{*url}", defaults: new { controller = "Home", action = "Index" } ); 

In my app.route.ts (angular routes), I just defined a couple of routes. My route is redirected to another route by default, for example

 export const router: Routes = [{ path: '', redirectTo: 'auctions/e231', pathMatch: 'full' }, { path: 'auctions/:id', component: AuctionComponent, children: [] } ]; 

When I launch the application, my server route / Home / Index is served fine which loads the angular application and the default route in my app.route.ts redirects me to / e 231 auctions and my final browser url becomes

 http://localhost:53796/auctions/e231 

Everything works as expected, but when I refresh the page with this URL, I get a server error for a resource that was not found, which is also expected because it is looking for a controller named Auctions that is not in MVC. I want to know why my spa spy route in RouteConfig.cs does not rise? There is also a better way to handle this script in asp.net mvc because I want to use some of my MVC controller actions like / Account / Login and others.

+6
source share
2 answers

Although, in my opinion, not the best approach, but still worked. I did this using restrictions on my route. I updated the default route:

 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, constraints: new { controller = "Home|Account|Upload|Resource" } // this is basically a regular expression ); 

Where I only had 4 MVC controllers (Home, Account, Upload, Resource). My spa backup route is by default, so if we enter anything other than these controller names, angular will try to find it on its route using the default path / Home / Index server.

I hope this helps someone.

+4
source

The problem is that when the page is refreshed, the first route will be used, because it will try to get a controller named Auctions. If you delete this first route configuration (by default) and use only the second (spa backup), it will work fine, as I used in my projects, I just set mvc routes before the spa backup that you want to redirect to other mvc.

+4
source

Source: https://habr.com/ru/post/1013502/


All Articles