Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 732
Andriy Drozdyuk Avatar asked Sep 25 '12 22:09

Andriy Drozdyuk


1 Answers

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.

like image 187
Isochronous Avatar answered Dec 17 '22 02:12

Isochronous