ASP.NET MVC combined with web API routing

I am trying to register multiple routes for web pages and for web APIs. Here are my settings:

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 }
        );
    }
}

This is how I register them in Global.asax

RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);

The problem is that the web API routing is not working, I get a 404 error, unless I register the WebAPI routes and then the ASP.NET MVC routes do not work and the web API routes work.

+4
source share
1 answer

Like @ChrFin outlined in his comments, if you register web API routes first, your MVC routes should work, because the default API route starts with an “api” by default.

, , routeTemplate -API {controller}/{id}, , , api , Global.asax -API MVC, Web API. "/anything" -API , , MVC .

, , - .

, MVC "mvc" MVC -API.

+7

All Articles