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.
-
I do it exactly as you do (WebAPI first) and it is working here. Do you do anything else with routing?Christoph Fink– Christoph Fink2014年07月24日 10:35:28 +00:00Commented Jul 24, 2014 at 10:35
-
I need both routes to work but works only first registereduser2412672– user24126722014年07月24日 10:44:51 +00:00Commented Jul 24, 2014 at 10:44
-
Yes, that is clear - and that works for me, so I was asking if you do anything else with the routing you did not show yet?Christoph Fink– Christoph Fink2014年07月24日 10:48:08 +00:00Commented Jul 24, 2014 at 10:48
-
No, just what I've showeduser2412672– user24126722014年07月24日 11:20:41 +00:00Commented Jul 24, 2014 at 11:20
1 Answer 1
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.
Comments
Explore related questions
See similar questions with these tags.