Friday, May 25, 2012

How to host WCF Data Service and Dot.Net RESTFull service together

This can be achieved by utilizing ASP.Net Dynamic Routing that can host both WebServiceHostFactory and DataServiceHostFactory just by couple of Global.assx and Web.config modifications
Alternative Titles 
Hosting WebServiceHostFactory DataServiceHostFactory togather 
The Problem 
We need to host WCF Data Service and a RESTFull web Service created from WCF REST Service Template 40(CS) in same project on different start up path like (http://localhost/myds and http://localhost/myrest). The real problem is that all the data services templates that are available adds .svc file that prevents dynamic routing. 

Use Case 
I have  a data service and a helper RESTfull service and want to host under same project that provides some auxiliary feature that data service do not provides like some graphics page

Solution (Step by Step)
Solution of this problem is quite simple but for me it took a day to figure out so thought to share with community.
  1. Create a data service solution that is based on ASP.Net Dynamic Routing 
  2. Add a new RESTFull  Project web service using  WCF REST Service Template 40(CS) 
  3. Copy RSETFull class file created above to Data Service Project 
  4. Add class entry to Routing Table
    private void RegisterRoutes()
            {
                // Edit the base address of Service1 by replacing the "Service1" string below
                RouteTable.Routes.Add(new ServiceRoute("MyRestService", new WebServiceHostFactory(), typeof(RESTFULService)));
                RouteTable.Routes.Add(new ServiceRoute("MyDataService.svc", new DataServiceHostFactory(), typeof(WCFDataService)));
            }
  5. Add some mandatory config entries to Data Service project
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true">
          <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        </modules>
      </system.webServer>
     
      <system.serviceModel>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
        <standardEndpoints>
          <webHttpEndpoint>
            <!--
                Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
                via the attributes on the <standardEndpoint> element below
            -->
            <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
          </webHttpEndpoint>
        </standardEndpoints>
      </system.serviceModel>

  6. we are all done.
  7. Ready for Testing 
    1. Navigate to   http://localhost:8888/mydataservice.svc/  to see that data service is working 
    2. Navigate to  http://localhost:8888/MyRestService/
    3. Navigate to REST help page  http://localhost:8888/MyRestService/help

No comments:

Post a Comment