Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF 4 - Soap and REST endpoints

Tags:

c#

.net

soap

wcf

I was looking at using the WCF REST Service Application template to host all of my RESTful web services, however, I would also like to be able to expose out my WCF services with a SOAP endpoint.

I can easily get my WCF RESTful services working in WCF 4 using the following example: http://christopherdeweese.com/blog2/post/drop-the-soap-wcf-rest-and-pretty-uris-in-net-4

Is this possible? I would imagine there should be a way in the Global.asax to wire up additional endpoints and specify if one is using basicHttpBinding. Do I need to not use the WCF REST Service Application template and create a standard Service Application and wire it all up via the config?

Thanks for any assistance.

like image 617
Brandon Avatar asked Apr 05 '11 13:04

Brandon


1 Answers

Although in most cases I wouldn't mix REST and SOAP endpoints, but I agree that in certain cases it's necessary. The answer to the question: yes, it's possible to mix them. There are two options you can use:

The call in Global.asax.cs which defines the route for the REST endpoint

`RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(),   typeof(Service1)))` 

defines essentially a service at the address /Service1. You can add a new "service", using the same service implementation, but using a different service host factory (instead of using WebServiceHostFactory, which defines a REST endpoint, you'd use your own):

public class SoapServiceHostFactory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);
        ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
        if (smb == null)
        {
            smb = new ServiceMetadataBehavior();
            host.Description.Behaviors.Add(smb);
        }

        smb.HttpGetEnabled = true;
        host.AddServiceEndpoint(serviceType, new BasicHttpBinding(), "soap");
        return host;
    }
}

And in global.asax.cs, RegisterRoutes:

    private void RegisterRoutes()
    {
        // Edit the base address of Service1 by replacing the "Service1" string below
        RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(), typeof(Service1)));

        RouteTable.Routes.Add(new ServiceRoute("SoapService", new SoapServiceHostFactory(), typeof(Service1)));
    }
  • If you actually want to have one "logical" service with two endpoints (I wouldn't recommend, since the previous approach is simple enough), you can again create a custom ServiceHostFactory, then in that factory you'd add two endpoints: one for REST (using WebHttpBinding/WebHttpBehavior), and one for SOAP (using BasicHttpBinding, for example).
like image 65
carlosfigueira Avatar answered Oct 12 '22 23:10

carlosfigueira