Removing svc extension of WCF REST service

What if we had a REST service implemented with WCF to retrieve some info about a user. The method would be called with the following url: “http://domain/service.svc/user/john”. Although this works perfectly and conforms to the REST guidelines, for some the svc extension is a thorn in the eye. Turns out it’s very easy to strip the svc extension with a HTTPModule. The module adds an eventhandler for the BeginRequest event of the application, each time a request is received the module checks if it is a call without the svc extension. If this is the case, it reroutes the request to service.svc with the specified parameters. To the outside world it will appear as if “http://domain/service/user/john” is called, while this resource actually does not exist.

public void Init(HttpApplication context)
{
   context.BeginRequest += delegate
   {
      HttpContext ctx = HttpContext.Current;
      string path = ctx.Request.AppRelativeCurrentExecutionFilePath.ToLower();
 
      if (path.Contains("/service/"))
      {
         int i = path.IndexOf('/', 2);
         if (i > 0)
         {
            string service = path.Substring(0, i) + ".svc";
            string parameters = path.Substring(i, path.Length - i);
            ctx.RewritePath(service, parameters, string.Empty, false);
         }
      }
   };
}

In our case service would equals “~/service.svc” and the paramaters variable would equal “/user/john”.

Hooking the HTTPModule into the web.config is done in the system.web/httpmodules element. In this case the module class is called ServiceRedirector.

<system.web>
   <httpModules>  
      <add name="ServiceRedirector" type="ServiceRedirector"/>
   </httpModules>
</system.web>

The HTTPModule above could be extended to support multiple services, but I leave that as an exercise for the reader.

Tags: ,

Leave a Reply