Monday, April 20, 2015

Error 8 'System.Web.Http.HttpConfiguration' does not contain a definition for 'MapODataServiceRoute'


In this article we fix the Error 8 'System.Web.Http.HttpConfiguration' does not contain a definition for 'MapODataServiceRoute', while adding a route to an ASP.NET application containing an OData Web API.



 System.Web.Http.HttpConfiguration MapODataServiceRoute


The error is originated after the Microsoft decision to create a new assembly to support the v4.0 version of the OData protocol, but keeping the OLD assembly which supported the version 3.0. The resultant side by side scenario where applications can reference to v3.0 and v4.0 simultaneously, can be the source of errors as the one we're fixing here. 
May be one of the more important changes here is , the "QueryableAttribute"  has now been renamed "EnableQueryAttribute". You can explore the assemblies differences in this MSDN article.

The new OData v4.0 assembly is "System.Web.OData" instead of the OLD "System.Web.Http.OData" , and the new package is called "Microsoft.AspNet.OData".

So the error appears after you configure the OData Endpoint at the WebApiConfig  Register()  :

Error  8 'System.Web.Http.HttpConfiguration' does not contain a definition for 'MapODataServiceRoute'

public static void Register(HttpConfiguration config)
        {
            
            ODataModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Note>("Notes");
            config.MapODataServiceRoute(
                routeName: "ODataRoute",
                routePrefix: "OData",
                model: builder.GetEdmModel());          

        }

The "routePrefix" sets the name of the Service Endpoint.

When you compile, you receive the following error message:



Because the Extension Methods in the new OData v4.0 assembly were moved to "System.Web.OData.Extensions", and the method "MapODataRoute" has been renamed to "MapODataServiceRoute", we must reference to that extensions namespace.
Therefore go to the usings section up in your C# file, and add the Extensions namespace to allow the use of the extension method that we are supposed to use:



using System.Web.Http.OData;
using System.Web.OData.Builder;
using System.Web.Http;
using System.Web.OData.Extensions;



That's all!!!!


By Carmel Shvartzman

עריכה: כרמל שוורצמן