Skip to content

Routing endpoints in WCF

pmartin7 edited this page Dec 23, 2016 · 9 revisions

Adding some documentation on a specific issue that was not well documented.

See here in MSDN: https://msdn.microsoft.com/en-us/library/ee358760.aspx?f=255&MSPPError=-2147217396

The goal was to be able to have clients call an endpoint like "http://.../api/..." instead of using the ugly "http://.../MusicGraphAPI.svc/..." endpoint. Turns out that we can do that using routing in WCF, and a little bit of ajax.

  • First, add a Global.asax file (empty) in the root of the web service solution.
  • In the file, add the following to specify the routing:

` <%@ Application Language="C#" %> <%@ Import Namespace="System.Web.Routing" %> <%@ Import Namespace="System.ServiceModel.Activation" %> <%@ Import Namespace="System.ServiceModel.Web " %>

    <script RunAt="server">
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }

    private void RegisterRoutes(RouteCollection routes)
    {
        routes.Add(new ServiceRoute("api", new WebServiceHostFactory(), typeof(MusicGraphExplorerAPI.MusicGraphAPI))); 
    }
</script>

`

  • We also need to import the routing module into the Web.config file:

<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> <handlers> <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd"/> </handlers> <directoryBrowse enabled="false"/> </system.webServer>

  • We also need to enable asp.net in the Web.config file:

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />

  • Finally, we need to decorate the service class (not the interface)

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class MusicGraphAPI : IMusicGraphAPI { ....

That works like a charm

Clone this wiki locally