Search code examples
c#asp.net-web-apiasp.net-web-api-routing

Routing Config for Web-API


I am creating a Web-API service using .Net 4.5.2.

I want to have the following URIs:

  • /api/v1/timeseries/{id}
  • /api/v1/timeseries/approval/{id}

With this, I expect to have two controllers:

  • TimeSeriesController
  • TimeSeriesApprovalController

Using default routing as below, I achieve my first desired outcome (/api/v1/timeseries/{id}), but I'm not sure how to achieve the second outcome. Can someone please show me how to amend the route config to deal with the second URI?

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/v1/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

Solution

  • One option would be to use your existing routes, and use the url like:

    /api/v1/timeseriesapproval/{id}
    

    Note that this perfectly matches your existing route:

    "api/v1/{controller}/{id}",
    

    where controller matches timeseriesapproval.

    Another option would be to setup a new route (prior to your existing one) specific for this need:

    config.Routes.MapHttpRoute(name: "PutThisBeforeYourExistingOneApi",
        routeTemplate: "api/v1/timeseries/approval/{id}",
        defaults: new { controller = "TimeSeriesApproval", id = RouteParameter.Optional } );