Andriy Drozdyuk
Andriy Drozdyuk

Reputation: 61121

Single page application route in ASP.NET MVC 4

I'm building a single page application with asp.net net mvc4 and javascript.

My javascript has it's own routing engine, so I would like to have all routes under root handled by javascript, and all routes under api handled by server side. I.e.:

/             <--- javascript handles 
/api          <--- ASP.NET MVC handles

However, I don't have a clue of how to tell ASP.NET MVC to not handle these routes, and what I tried so far doesn't even run:

        routes.MapRoute(
            name: "Client",
            url: "/",
            defaults: new { controller = "Home", action = "Index",  }
        );

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

Any ideas are welcome, thanks!

Upvotes: 6

Views: 9191

Answers (1)

Isochronous
Isochronous

Reputation: 1090

You can't have defaults for parameters that don't exist in the route URL, unless you use a catch-all parameter. You'd also need to create your API route first to avoid it being consumed by the catch-all route.

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

routes.MapRoute(
    "Default", // Route name
    "{*catchall}", // URL with parameters
    new { controller = "Home", action = "Index" } // Parameter defaults
);

update: I should mention that in this case, .NET MVC will still forward any requests not matching "API" on to "Home/Index," which in your case should serve up the entry point of your client-side MVC framework.

Upvotes: 17

Related Questions