MVC instrumentation & WebApi attribute routing for Sitecore 7.5

1k views Asked by At

I have been trying to get WebApi working with Sitecore 7.5 (I was able to get the same code working with 7.2) I have left in the config the reference to MVC 5.1 and I am getting the following exception when I try to access a route mapped with an attribute:

[RoutePrefix("test/api/Other")]
[Route("{action=Get}")]
public class OtherController : ApiController
{
    [HttpGet]
    public string GetId()
    {
        return "test";
    }
}

Message: "An error has occurred.", ExceptionMessage: "Value cannot be null. Parameter name: key", ExceptionType: "System.ArgumentNullException", StackTrace: " at System.Collections.Generic.Dictionary2.FindEntry(TKey key) at System.Collections.Generic.Dictionary2.TryGetValue(TKey key, TValue& value) at Sitecore.Services.Infrastructure.Web.Http.Dispatcher.NamespaceHttpControllerSelector.SelectController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()"

The code that I have in the application start is the following:

protected void Application_Start(object sender, EventArgs e)
{
    GlobalConfiguration.Configure(ConfigureRoutes);
}

public static void ConfigureRoutes(HttpConfiguration config)
{
    GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
    GlobalConfiguration.Configuration.Formatters.Clear();
    GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
}

any help would be appreciated....

1

There are 1 answers

0
Søren Kruse On

Starting with Sitecore 7.5 they are replacing the default IHttpControllerSelector with their own NamespaceHttpControllerSelector which doesn't support Attribute Routing.

However, it is possible to workaround this. You have to create your own version of NamespaceHttpControllerSelector and patch it into the initialize pipeline after this one:

Sitecore.Services.Infrastructure.Sitecore.Pipelines.ServicesWebApiInitializer, Sitecore.Services.Infrastructure.Sitecore

I have created both a Sitecore package and a NuGet package to do this depending on what you prefer and what your needs are.

The "Custom" package creates the code in your solution, so you can edit it yourself if you have special needs. The Sitecore package and the standard NuGet package just drops my assembly in the bin folder and creates a config file in App_Config\Include which patches the initialize pipeline.

If you want to look at the code, or read a bit more about the issue, have a look at my GitHub repository.