August 11, 2006

How to convert existing ASMX service to WCF?

Suppose you have asmx webservice code as below:

[WebService(Namespace=”http://tempuri.org/asm”)]

public class TestService : System.Web.Services.WebService{

[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}

Steps to convert above asmx service in wcf are:

1. Create a .svc file in your virtual directory.

Create a .svc file in your virtual directory that contains the following declaration same as asmx file for traditional web service:

<%@ServiceHost"Language=”C#” Service=”TestService” %>

2. Add WCF attributes.

Add [ServiceContract] to the classes you want to expose through WCF, and [OperationContract] to the methods as shown:

[ServiceContract(Namespace=”http://tempuri.org/asm/wcf”)]
[WebService(Namespace=”http://tempuri.org/asm”)]
public class TestService : System.Web.Services.WebService{
[WebMethod]

[OperationContract]
public string HelloWorld() {
return "Hello World";
}
}


3. Modify web.config file

Add following code in web.config file to add an HTTP binding for your service:

<system.serviceModel>
<services>
<service type=”TestService”>
<endpoint binding=”basicHttpBinding” contract=”TestService” /> </service>
</services>
</system.serviceModel>