How to stop ASP.NET MVC from interfering with Angular routing?

306 Views Asked by At

I am trying to get Angular to work with ASP.NET MVC by following this tutorial. So far, after a lot of trial & error I was able to get it to work for the most part. However, the ASP.NET MVC routing is still causing me a lot of trouble and I don't know what to do about this. For example, when I navigate to another page in the frontend, it works fine but as soon as I refresh the page I get a 404 error, because the backend does not know what to do with the Angular route.

I also noticed that a few minor things like for example the hamburger menu icon in the Angular application are not displayed properly. Instead of the icon it just displays the text "menu". I assume that this is also related to the routing not working properly.

This is how my RegisterRoutes implementation looks like:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Angular", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        name: "Angular",
        url: "{*url}",
        defaults: new { controller = "Angular", action = "Index" }
    );
}

The second route mapping is just an attempt to solve the routing problem which I found in this SO question, but it does not seem to be working in my case.

In my backend, I have the following Index.cshtml to return the Angular page to the web browser:

@{
    Layout = null;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Home</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    @Styles.Render("~/bundles/angular-css")
</head>
<body class="mat-typography">
    <app-root></app-root>
    @Scripts.Render("~/bundles/angular")
</body>
</html>

To return this as a View, I implemented the following controller:

public class AngularController : Controller
{
    // GET: Angular
    public ActionResult Index()
    {
        return View();
    }
}

How can I configure the routing in ASP.NET MVC so it does not interfere with the Angular routing?

0

There are 0 best solutions below