Search code examples
angulariisurl-routing

angular app 404s when navigating with url manually


I've got an Angular 7 website that uses MVC and is hosted on IIS.

Since we're utilizing MVC, we serve up index.html within _Layout.cshtml (using @RenderBody()) which then uses a controller to serve up index.cshtml which houses the <app-root></app-root> tags

The app works just fine, however, when trying to navigate to a url manually (e.g. http://my-site.com/endpoint) is accessible when using a navigation control, but entering it manually within the address bar, it throws a 404 error.

I keep seeing "Redirect to index.html" but index.html exists within the angular application and isn't a reachable url unless navigating to http://my-site.com/index.html. So how do I serve my endpoint view by redirecting to index.html? How do I even do that?

I've done a fair amount of reading and trying things here on SO, but nothing really matches my issue, and I don't seem to be making any headway.

Let me know if you need to see my code, but from what I read, this needs to be handled on the hosting server. Any help would be very appreciated.


Solution

  • I ended up finding a solution to this issue.

    If you've got your angular site wrapped in an MVC application, you can setup MVC routes in startup.cs to force any non-MVC route to use the controller/view that serve up the angular application.

    This will allow you to navigate to an angular route using a manually entered URL, however it forces a page reload. (for my purposes, this isn't an issue).

    below is my code

    In Startup.cs:

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "mvc",
            template: "{controller}/{action}");
    
        routes.MapRoute(
            name: "default",
            template: "{*url}",
            defaults: new { controller = "Home", action = "Index" });
     });