简体   繁体   中英

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?

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.

If I understand correctly, you want the'/user/5' to be given to the routing engine in Angular. If this is the case, Angular deals with the route after the hash. This means the route you want is

http://myapp.com#/user/5

You will also need to configure the $routeProvider properly with a route like:

angular.module('yourApp', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/user/:id', {templateUrl: 'SOME_HTML_FILE'}).
      otherwise({redirectTo: '/'});
}]);

You would then need to get the route param out in the controller:

function someController($scope, $routeParams) {
  if($routeParams.id){
       alert('Super Fly!');
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM