Monday, April 23, 2012

Extensionless REST URL in Microsoft Windows Communication Foundation

Extensionless REST URL (.SVC) in Microsoft Windows Communication Foundation


Independent of Programming Language in which Rest Application is implemented , its URL does not have any extensions in production environments but when you implement Rest application using Microsoft Windows Communication Foundation (WCF),  URL ends with .SVC .

If you look at the URL its very easy to recognize that the application is built using Microsoft WCF. There are many ways of removing .SVC but they are in-efficient, efficient way of implementing this is described below.

1) ISAPI Handler : This requires third party software to be installed on the Windows server  more over its in-efficient.  ISAPI modules intercept each and every request, so the more modules you install, the slower each request becomes
2) Wildcard Mapping:  it suffers from scalability problem and there's 30% drop in performance .

For Example: 

http://localhost:52930/SampleService/HelloWorld  instead of

http://localhost:52930/SampleService.svc/HelloWorld

To remove service extension (.svc), write a HTTP Module and remove the extension and rewrite the path.
Now to remove .svc follows below steps

1.     Add a class in WCF Application project. 
2.    Add the namespace System.Web
3.    Implement the class from  IHttpModule

Removesvc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WcfService7
{public class Removesvc : IHttpModule 
    {public void Dispose()
        {
        }public void Init(HttpApplication context)
        {
           

            context.BeginRequest += delegate{
                HttpContext cxt = HttpContext.Current;string path = cxt.Request.AppRelativeCurrentExecutionFilePath;int i = path.IndexOf('/', 2);if (i > 0)
                {string a = path.Substring(0, i) + ".svc";string b = path.Substring(i, path.Length - i);string c = cxt.Request.QueryString.ToString();
                    cxt.RewritePath(a, b, c, false);
                }
            };
        }
       
    }
}

1
4) Now we need to add the HTTP Module in configuration file of WCF Service. 

Web.Config




  
    
   
  
  
    
      
        
        
          
          
          
        
      
    
    
  
 
    
      
         
    

Where, RemoveSvc is name of the class implementing IHttpModule and WcfService7 is the project name (namespace)

5)  Now host the service in IIS.   
Now when you open WCF REST Service in browser, you can see you are able to  call the service without extension , 

http://localhost:52930/SampleService/HelloWorld 

Now we can expose Rest URL's without .svc extensions even though they are deployed on to WCF.

Popular Posts