wolfgang ziegler


„make stuff and blog about it“

How to remove the .svc extension for WCF Webservices

April 21, 2010

Many developers do not like the fact that a WCF Webservice URL ends with a mandatory “.svc” extension. That’s why the WCF team added a feature to be able to get rid of the “.svc” extension in .NET 4.0.

But even for older versions of the .NET framework there is a way to avoid URLs with this extension by implementing the interface IHttpModule and using the RewritePath method of the HttpContext class.

using System.Web;

namespace WCFServiceWebRole1
{
  public class ServiceRedirector : IHttpModule
  {
    public void Init(HttpApplication app)
    {
      app.BeginRequest += delegate
      {
        HttpContext ctx = HttpContext.Current;
        string path = ctx.Request.AppRelativeCurrentExecutionFilePath;
        path = path.Replace("Service", "Service1.svc");
        ctx.RewritePath(path, null, ctx.Request.QueryString.ToString(), false);
      };
    }

    public void Dispose()
    {
    }
  }
}

 

This code class is obviously just intended for demo purposes and URLs have to be checked more thoroughly before they are actually modified.

If this module gets loaded by IIS, it routes e.g. the URL /Service1">http://<host>/Service1 to /Service1.svc">http://<host>/Service1.svc, where the Webservice is actually accessible. The only thing left to do is modifying the web.config file of the WebService project to actually load the HTTP module into IIS. For this purpose, the <modules> sections of <system.webServer> has to be extended with the newly created HTTP module.

<system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <modules>
    <add name="ServiceRedirector" type="WCFServiceWebRole1.ServiceRedirector"/>  </modules>
</system.webServer>