Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 Route for Bookmarked Angular SPA URLs

I'm trying to build a single-page application in AngularJS with client-side routing done in HTML5 mode. In case users ever bookmark a page on my site, I understand that I need a basic server-side routing scheme but I really want it to just always serve up my single homepage and propagate the same URL to the client-side routing piece.

This catch-all route works perfectly on simple URLs that are only one deep:

routes.MapRoute(
    "Default", // Route name
    "{*catchall}", // URL with parameters
    new { controller = "Home", action = "Index" } // Parameter defaults
);

Example URLs:

http://myapp.com/moreInfo
http://myapp.com/contactUs

"moreInfo" and "contactUs" are just named routes within Angular. The only real entry point to the single-page application is at http://myapp.com. So far, this all works very smoothly.

When I try to go more than one route deep, though, the application goes into an infinite loop:

http://myapp.com/user/5

Is this because my server-side route is not sufficient to "pass along" the "user/5" URL to my client application? Do I need to do anything special to make sure that no matter how deeply nested the URL is, it gets passed along to my SPA properly?

like image 346
blaster Avatar asked Oct 02 '13 17:10

blaster


1 Answers

The problem is not with the routing configuration, I have a similar setup with angular js and mvc 4, and the route below works fine.

routes.MapRoute(
  name: "Application",
  url: "{*url}",
  defaults: new { controller = "Home", action = "Index" },
  namespaces: new[] { "MyApp.Web.Controllers" });

Do you have the html5Mode set to true in the angular config method?

$locationProvider.html5Mode(true);

You might try to send a get request to your app with fiddler and look at the response. If it is a 301 or 302, then you have a server side redirection loop issue. If it is 200, then your angular/js code might be the issue.

like image 166
Chris Tesene Avatar answered Sep 28 '22 08:09

Chris Tesene