1

I have an angular application (backed by .Net 4.6 and MVC5) with routes such as

/admin
/admin/manageusers
/admin/export

I can reach these via client side routing if my asp.net application sends me to /Admin.

However, if I refresh the page the MVC routing engine doesn't know where to send me and I end up with a 404.

I've tried as many variations of this as I can think of with no success.

context.MapRoute(
    "Admin_root",
    "Admin/{*url}",
     new { area = "Admin", controller = "Admin", action = "Index" });

Is there a way to tell MVC to ignore what would traditionally be the controller and action and just continue with the Index action?

Is there a way to build a catch all route that will ignore what would typically be the controller and action?

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Joe
  • 5,389
  • 7
  • 41
  • 63

1 Answers1

4

The ASP.NET Core Angular project template includes a call to MapSpaFallbackRoute for exactly this purpose. You can see a detailed explanation of this in Github.

Here's the code example:

app.UseStaticFiles();

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");

    routes.MapSpaFallbackRoute(
        name: "spa-fallback",
        defaults: new { controller = "Home", action = "Index" });
});

Here's part of the explanation:

Then, since MapSpaFallbackRoute is last, any other requests that don't appear to be for static files will be served by invoking the Index action on HomeController. This action's view should serve your client-side application code, allowing the client-side routing system to handle whatever URL has been requested.

You'll need a reference to Microsoft.AspNetCore.SpaServices if you don't already have it.

EDIT: Since you've specified that you're not using ASP.NET Core, take a look at this asnwer: How to use ASP.NET MVC and AngularJS routing?. It's a similar approach to what I described but for ASP.NET MVC 5. The solution suggested there does seem to basically be the same as what you've described, however.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203