As mentioned in my earlier
post of web services in ASP.NET, web services support HTTP protocol and do not maintain any state information.
However WCF (Windows Communication Foundation) services can be hosted on different types of application and more secured compared to web services.
WCF service endpoint is composed of
A : Address -> link to service endpoint address -> where the endpoint can be found
B : Binding -> port type -> how a client can communicate with the end point
C : Contract -> message -> message exchange patterns and operations -> available operations
Simple example of WCF service is explained below. This example will give you an idea how WCF works. For more complex functionalities, keep visiting my blog.
1. Create WCF service application as shown below.
2. WCF service contract (C : Contract) is implemented in Interface section IService1. So methods in this interface will help user to understand available operation with this service.
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
[OperationContract]
int sum(int num1, int num2);
}
Note : WCF interface by default has two methods GetData() and GetDataUsingDataContract().
Also interface IService1 is defined public so that it should be accessible to code outside this project.
2. This interface is inherited in class Service1
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
public int sum(int num1, int num2)
{
return num1 + num2;
}
}
3. Run and execute this WCF service you can see WCF service URL : This is Address part of WCF.
4. Now create another website project and add service reference for our earlier created WCF service to this newly created project as follows.
5. Write following code and execute to see the result.
protected void Button1_Click(object sender, EventArgs e)
{
ServiceReference1.Service1Client sc = new ServiceReference1.Service1Client();
int sum=sc.sum(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text));
Label1.Text = sum.ToString();
}