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> </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