Habitat Sitecore

Web Api And MVC Routes in Habitat sitecore project

First of all I would like to describe the main problem here which is creating Web API and MVC routes which will handle the corresponding requests correctly.

From  technology point Web API is designed on much more on Lower level then MVC, to be clear it is not better or worse but they are used for different things, however MVC is build on top of the Web Api.

But as the MVC comes on top of the Web API routes that are different first go through the MVC Routes and if they cannot be found then go deeper in the Web Api routes.

Imagine if you have  two routes with same names  /GetMyList in MVC and  /GetMyList in Web API, there is a big chance that the route handler will be confused.

In Sitecore regular instance you can just define the route with RouteTable.Routes.MapRoute() or RouteTable.Routes.MapHttpRoute() and because there is no other api routes they will work, however in habitat you need to be more careful which function do you use in order create route.

This is because habitat already comes with the a lot of different pipeline processors which are pre-configured and this can be a problem when mapping new routes especially if you don’t know or don’t consider the already mapped routes from habitat.

Best practice in habitat would be to separate the web api routes from MVC routes and also always use the MapHttpRoute for Web API and MapRoute For MVC.

Keep in mind that one other good practice is to always separate Web API and MVC routes in separate folder and also the names of the routes should bed different. Please see the attached picture.

One thing I forgot to mention which is really important is that in habitat for every project have you maps the Web Api or MVC routes in the  RegisterWebApiRoutes.CS in the pipeline folder of that project, and normally  add the “pipeline”(RegisterWebApiRoutes.cs) to the pipeline processor in app_config/include/feature/nameOftheProject.Config in order to be properly executed and register the proper routes.

I hope that you will find this post useful and it will give you boost up if you stuck with Web Api and MVC Routes in Habitat project.