Reputation: 1479
I'm trying to register multiple routes for Web Pages and for Web API. Here's my config's:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Registration Courses SPA",
url: "Registration/Courses",
defaults: new {controller = "Registration", action = "Index"});
routes.MapRoute(
name: "Registration Instructors SPA",
url: "Registration/Instructors",
defaults: new { controller = "Registration", action = "Index" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
and
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate:"api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Here's how I register them in Global.asax
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
The problem is that Web API routing not working, I'm getting 404 error, unless I register WebAPI routes first then ASP.NET MVC routes not working and Web API routes working.
Upvotes: 10
Views: 7081
Reputation: 753
Like @ChrFin stated in his comments, if you register the Web API routes first your MVC routes should still work because the default Web API route begins with "api".
I had the same problem but it was because we changed the routeTemplate
of the default Web API route to {controller}/{id}
because we wanted that to be the default because the purpose of our app is to be an api for other apps. In our Global.asax file the Web API routes are registered before the MVC routes, which is the default for any new Web API application. Because "/anything" matches the default Web API route, route handling stops so our MVC routes never get a chance to get matched.
The key point is that route handling stops if a route gets matched - even if there's no matching controller.
To solve our problem we prefixed our MVC routes with "mvc" and registered our MVC routes before the Web API routes.
Upvotes: 11