Search code examples
asp.netasp.net-mvcasp.net-web-apiasp.net-mvc-routing

ASP.Net WebAPI Routing Configuration


I have defined the following route:

GlobalConfiguration.Configuration.Routes.Add(
    "iOS Service",
    new HttpRoute("ios/{controller}/{action}/{id}", new HttpRouteValueDictionary { { "id", RouteParameter.Optional } })
);

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    name: "iOS Service Documents",
    routeTemplate: "ios/getfulldocumentstructure",
    defaults: new { controller = "Documents", action = "GetFullDocumentStructure" }
);

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    name: "iOS Service AppInfo",
    routeTemplate: "ios/appinfo",
    defaults: new { controller = "AppInfo", action = "GetAppInfo" }
);

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    name: "iOS Service Html",
    routeTemplate: "ios/html/{language}/{contentId}",
    defaults: new { controller = "Html", action = "GetHtml", language = RouteParameter.Optional, contentId = RouteParameter.Optional }
);

With the following controller:

public class HtmlController : ApiController
{
    [HttpGet]
    public string GetHtml(long language, long contentId)
    {

        return "Hello";
    }
}

If I hit the service using http://localhost/ios/html?languageId=1033&contentId=12345 the GetHtml action fires.

If I hit the service using http://localhost/ios/html/1033/12345 I get an error that no matching action is found in the controller.

What I am doing wrong?


Solution

  • Moving the catch all route to the end fixed the issue. The calls were hitting the wrong controller:

    GlobalConfiguration.Configuration.Routes.MapHttpRoute(
        name: "iOS Service Documents",
        routeTemplate: "ios/getfulldocumentstructure",
        defaults: new { controller = "Documents", action = "GetFullDocumentStructure" }
    );
    
    GlobalConfiguration.Configuration.Routes.MapHttpRoute(
        name: "iOS Service AppInfo",
        routeTemplate: "ios/appinfo",
        defaults: new { controller = "AppInfo", action = "GetAppInfo" }
    );
    
    GlobalConfiguration.Configuration.Routes.MapHttpRoute(
        name: "iOS Service Html",
        routeTemplate: "ios/html/{language}/{contentId}",
        defaults: new { controller = "Html", action = "GetHtml", language = RouteParameter.Optional, contentId = RouteParameter.Optional }
    );
    
    GlobalConfiguration.Configuration.Routes.Add(
        "iOS Service",
        new HttpRoute("ios/{controller}/{action}/{id}", new HttpRouteValueDictionary { { "id", RouteParameter.Optional } })
    );