Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single page app in AngularJS and ASP.Net works fine, but when I refresh my page in the browser I get 404 errors

So I've set up an HTML5 single page application, and it's working well. The page is at /App/ and when some one goes to content it looks like /App/Content/1234.

One problem: If the user refreshes the page the server can't find that URL because it doesn't actually exist. If I send them to /App/#/Content/1234, they're golden, but what is the best way to do this? I have a LOT of different styles of URL under /App.

What is the best way to globally catch any request under ~/App/(.*) and redirect it to ~/App/#/$1?

The only route registered in MVC is the standard OOTB route.

like image 694
Ben Lesh Avatar asked Aug 03 '12 00:08

Ben Lesh


2 Answers

Sounds like your server is not re-writing the urls to the app's base URL.

The URL re-writing needed on the web server is server-dependent. For Apache, you'd use mod_rewrite.

Instead, switch Angular to the "Hashbang mode" (the default) so the urls will all store the local state after the # in the url.

I don't want my apps to require server configuration changes, so I recommend hashbang mode.

See AngularJS docs. See section "Hashbang and HTML5 Modes" The HTML5 mode section describes all the configuration issues needed to support HTML5 mode for the urls.

like image 171
Larry K Avatar answered Oct 22 '22 06:10

Larry K


This awesome dude describes how to fix this here.

In brief:

  1. Remove MVC nugets (unless you use MVC controllers for anything) - you can keep the Web API nugets. Keep WebPages and Razor packages. Also delete MVC controllers and views.
  2. You can keep using .cshtml files with some web.config modifications. You'll need this for bundling.
  3. Finally you add a rewrite rule on web.config to point all urls (excluding content, images, scripts etc) to index.html
like image 25
georgiosd Avatar answered Oct 22 '22 07:10

georgiosd