Using System.Web.Routing with Data Services (OData)

So you like the new OData protocol and the implementation in WCF Data Services… but you hate having a “.SVC” extension in the URI?

How do you get rid of the .svc extension with WCF Data Services?

Simple… Just use the new ServiceRoute class.

For this example, I’m using a project from my MIX10 session Driving Experiences Via Services using the .NET Framework

The sample includes a simple WCF Data Service that returns information about a conference.

image

As you can see I’ve put the service under the Services folder.  To access it you have to browse to https://localhost:62025/Services/Conference.svc/

The default behavior of the URI in this case is that the folder and file name in the web site are used to create the URI.  But if you don’t like that with .NET 4 you can just create a route. 

Just add a Global.asax file to your site and add the following code

 public class Global : System.Web.HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes();
    }

    private void RegisterRoutes()
    {
        DataServiceHostFactory factory = new DataServiceHostFactory();
        RouteTable.Routes.Add(
            new ServiceRoute("Conference", factory, typeof(Conference)));
    }
}

This code creates a route for the URI https://localhost:62025/Conference that will use the DataServiceHostFactory to create our WCF Data Service class which is the type Conference.

Simple, easy and very cool…