0
votes

I have a single page application that has one MVC file index.cshtml which is served by the Home controller and Index method. All the logon, logoff and data requests are served by WebAPI. Can someone confirm if I am setting up my routing correctly. Here is what I have:

RouteConfig.cs

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

        routes.MapRoute("DefaultRedirect",
            "",
            new { controller = "Home", action = "Index" }
        );

        routes.MapRoute(
            "catchall",
            url: "{*url}",
            defaults: new { controller = "Home", action = "Index" });

    }

WebApiConfig.cs

    public static void Register(HttpConfiguration config)
    {

        config.Routes.MapHttpRoute(
            name: ApiControllerOnly,
            routeTemplate: "api/{controller}"
            );

        config.Routes.MapHttpRoute(
            name: ApiControllerAndId,
            routeTemplate: "api/{controller}/{id}",
            defaults: null, //defaults: new { id = RouteParameter.Optional } //,
            constraints: new { id = @"^\d+$" } // id must be all digits
            );

        config.Routes.MapHttpRoute(
            name: ApiControllerAction,
            routeTemplate: "api/{controller}/{action}"
            );

        config.Routes.MapHttpRoute(
            name: ApiControllerActionAndId,
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: null, //defaults: new { id = RouteParameter.Optional } //,
            constraints: new { id = @"^\d+$" }
            );

    }

Global.asax

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        WebApiConfig.CustomizeConfig(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

What I am not sure of is the first file that handles MVC routes. Do I need to have just one route that makes everything go to Home Controller and Index method.

Also should I in the MVC routing ignore those requests that start with api ?

1

1 Answers

3
votes

You should not serve your SPA page as index.cshtml (because that means that it is being compiled to the respective class on the server that will serve the response)

It should be served as index.html and all data that it requires should be fetched by AJAX calls to the server.