Vue App and MVC Routing w/Visual Studio ASP.NET Core


Vue.js SPA routing conflicts with MVC routing. Short article reviewing the options, and an approach on how to get both working nicely together.

- November 30, 2018

Rest of the Story:

###What page is loaded on starting the application.

The default route for this VS.NET ASP.NET Core application is the public/index.html with the following setup in the Startup.cs

app.UseSpa(spa => {
spa.Options.SourcePath = "ClientApp";

if (env.IsDevelopment())
{

// run npm process with client app
spa.UseVueCli(npmScript: "serve", port: 8080);

}
});

If you have a HomeController and a Views/Home/Index.cshtml view, when the application starts via F5 it will route by default to http://localhost:50557 or http://localhost:50557/index.html and if you want to navigate to your controller/view you can navigate to http://localhost:50557/Home/Index Essentially it will default to the vue index.html page in this scenario.

image_thumb[1]

Navigating to http://localhost:50557/home/index will navigate to the MVC view, however if you want this route to navigate the vue app you can add, which would redirect the user from the MVC view to the vue app again.

public IActionResult Index()
{
return Redirect("~/index.html");
}

If you have a HomeController AND and you add MapSpaFallbackRoute reference within the Startup.cs similar to the following, starting via F5 the site will navigate to http://localhost:50557/ and land on the Views/Home/Index.cshtml This really is the reverse of the above scenario. In this case it will default to the MVC view and you have to explicitly navigate to the /index.html for the vue app.

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

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

image_thumb[2]

If you want to navigate to your vue app, you must explicitly reference http://localhost:50557/Index.html Any invalid routes will default to the Home/Index view.

image_thumb[3]

There are a number of combinations and can be confusing.

Primarily, both the vue app and MVC navigation work fine. It really just depends on if you want the MVC to be the default route, or the vue app index.html page.