C# & ASP.NET MVC default controller for partial Vue Single Page Application

Part of my ASP.NET MVC application uses Vue together with Vue routing.

Example:

/account <-- is from AccountController
/account/Extra <-- if from vue-router.

Whenever I type in the url in my browser /account/extra, I get a 'page can’t be found' error. Which is correct because ASP.NET MVC only knows about /account. But this is a problem for me.

My routing:

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}",
                new { controller = "Home", action = "Index" });
            endpoints.MapControllerRoute(
                name: "api",
                pattern: "api/{controller=Home}/{action=Index}/{id?}",
                );
            endpoints.MapRazorPages();
        });

I found no clue on stackoverflow and google search didn't get me far. Maybe I am searching for the wrong keywords?

Anyway, someone have any experience with this?

2 answers

  • answered 2021-10-24 19:17 Jacob

    To enable client-side routes, a fallback path can be configured to pass any unresolved server-side routes to the client app.

    In the Configure method of the Startup class, you can add

    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseEndpoints(endpoints =>
     {
       endpoints.MapControllers();
       endpoints.MapFallbackToFile("/index.html");
     });
    

  • answered 2021-10-24 19:23 Serge

    try to use attribute routing

    [Route("[controller]/[action]")]
    [Route("[controller]/extra/[action]")]
    public  class AccountController : Controller
    {
      [Route("~/[controller]")]
      [Route("~/[controller]/extra")]
      public IActionResult Index () {} //your home page for Account Controller
    
      [Route("{id}")]
      public IActionResult MyAction (int id) {}
    }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum