Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Routing with ASP.NET MVC

I am trying to use ASP.NET MVC (not core) with AngularJS 2 and having some issues with the routing.

First in RouteConfig.cs, I have following routes defined

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 have just defined a couple of routes. My default route redirects to the other route like

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

When I run the application, my server route /Home/Index is served up fine which loads the angular application and default route in my app.route.ts redirects me to auctions/e231 and my browser's final 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 resource not found, which is also expected because it looks for a Controller named Auctions which is not present in MVC. I want to know why my spa-fallback route in RouteConfig.cs doesn't picked up? Also is there a better way to handle this scenario in asp.net mvc because I want to able to use some of my MVC controller's actions like /Account/Login and others.

like image 593
Ali Baig Avatar asked Dec 25 '16 03:12

Ali Baig


1 Answers

The problem is that when you refresh the page, the first route will be used, because it will try to get a controller with name Auctions. If you remove that first route configuration (Default) and only use the second (spa-fallback), it will work ok, that's how I used in my projects, only put before spa-fallback other mvc routes that you want to redirect to other mvc controllers.

like image 158
Darian Serrano Avatar answered Sep 23 '22 14:09

Darian Serrano