Adding WCF REST services to existing ASP.NET web application

April 06, 2011

...

If you want to create a new WCF services application with REST support, the WCF REST Templates are brilliant. However, if you have an existing ASP.NET application from which you want to expose REST services, there are a few manual steps you need to take to get it up and running:

Add assembly references

Add references to the following assemblies in your existing web project:

  • System.ServiceModel
  • System.ServiceModel.Activation
  • System.ServiceModel.Web

Create service class

Create a new service class where you will implement the service:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class LetterService
{
    [WebGet(UriTemplate = "")]
    public List<string> GetList()
    {
        return new List<string>{"a", "b", "c"};
    }
}

Register service route

In Global.asax.cs, define a route to the service:

void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.Add(new ServiceRoute("letter", new WebServiceHostFactory(), typeof(LetterService)));
}

Enable ASP.NET compatability

Add the following to web.config:

<configuration>
   <system.serviceModel>
      <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   </system.serviceModel>
</configuration>

…and you are good to go! The service will be available on http://<server>/letter

Optional: enable help

In order to get a nice help page for clients connecting to the service, add the following under the system.serviceModel element in web.config:

<standardEndpoints>
   <webHttpEndpoint>
      <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
   </webHttpEndpoint>
</standardEndpoints>

Then, help will be available on http://<server>/letter/help.


Profile picture

Written by Vidar Kongsli who is a software professional living in Oslo, Norway. Works as a consultant, system architect and developer at Bredvid. You should follow him on Twitter