Web API routing in Sitecore 8.2

1.9k views Asked by At

I migrated a sitecore 7.2 application to sitecore 8.2 using the express migration tool. After the migration Web API routing stopped working. I'm using below given method to map the routing

 [UsedImplicitly]
        public class ConfigRegister
        {
            /// <summary>
            /// Startup method to bind all configurations for site core pipeline.
            /// </summary>
            /// <param name="args"></param>
            public virtual void Process(PipelineArgs args)
            { RouteConfig.RegisterRoutes(RouteTable.Routes);
     }
        }

Then registering it using following code snippet

public static void Register(HttpConfiguration config)
        {
         config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "ControllersApi",
                routeTemplate: "WebApi/CustomerPortal/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

I'm getting error A route named 'MS_attributerouteWebApi' is already in the route collection. Route names must be unique. Parameter name: name.

But when I comment the line

config.MapHttpAttributeRoutes();

I'm getting error {"Message":"An error has occurred.","ExceptionMessage":"The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes()\r\n at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request)\r\n at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)"}

Your help to solve this issue is highly appreciated

1

There are 1 answers

2
Marco On

I assume you have this under the initialize pipeline, correct?

This is what we've done before and works on 8.2:

    public void Process(PipelineArgs args)
    {
        HttpConfiguration httpConfig = GlobalConfiguration.Configuration;
        httpConfig.Routes.MapHttpSessionRoute("WebApiRoute", "webapi/{controller}/{action}/{id}", true, new { id = RouteParameter.Optional });          
    }

If the above doesn't work,try this (per Habitat):

public void Process(PipelineArgs args)
{
     RouteTable.Routes.MapHttpRoute("Feature.Demo.Api", "api/demo/{action}", new
        {
           controller = "Demo"
        });
}