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

Time:10-25

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?

CodePudding user response:

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");
 });

CodePudding user response:

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) {}
}
  • Related