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

Web API routing to match namespace


I am creating a Web API for internal consumption at my place of employment. I have not created a Web API before.

I was wondering, is it possible to configure my "WebApiConfig.cs" file (where i handle my default routing) to default to the namespace route of my controller?

For example:

CalendarDatesController.cs

namespace SampleWebService.Controllers.CalendarServices {
public class MilestoneDatesController : ApiController  {
    public DateTime Get() {
        return new DateTime();
    }
}

}

WebApiConfig.cs (default)

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

        // Web API routes
        config.MapHttpAttributeRoutes();

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

WebApiConfig.cs (proposal)

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

        // Web API routes
        config.MapHttpAttributeRoutes();

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

In my "proposal" it would include 'CalendarServices' in the path, however, if i make another folder, I would like that other folder to be in it's place. I would just like it to default to - api/ControllersParentFolder/Controller/id


Solution

  • Although this article is based on versioning, you should be able to use it for your needs.

    https://devblogs.microsoft.com/aspnet/asp-net-web-api-using-namespaces-to-version-web-apis/