0

Why does the order matter here?

If I do routes.MapHttpRoute first then my api works fine.. if I put it after routes.MapRoute it doesn't like it and I throws me the error:

The resource cannot be found.

Once long as I put mapHttpRoute before MapRoute , it works fine.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace WebApplication1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //THIS FIRST
            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // THIS SECOND
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );            

        }
    }
}

dfsd

psj01
  • 3,075
  • 6
  • 32
  • 63
  • 1
    The 2nd (Default) match any url containing 0, 1, 2 or 3 segments (if its first, your DefaultApi route would never be hit) –  Mar 21 '18 at 21:14
  • So If i have my api controllers sitting inside another folder like folder1/api/{controller}/{id}.. that should work ? – psj01 Mar 21 '18 at 21:22
  • No, that makes no difference. If you swapped then and the url is say `/api/Product/1` to would match the Default and try to execute the `Product` method of `ApiController` (which does not exist) –  Mar 21 '18 at 21:27

0 Answers0