Name Property On WCF Contracts

Services in projects are quite common these days, as they help the other components/systems to interact with your system and exchange information. Your service may contain many methods which reflects your system functionality, like GetProductsByCategoryId, UpdateSalesOrderByOrderId etc.
However, it may not be a good idea to share these names with other systems, especially if they are any external systems. In such a case, we can easily avoid this situation when we are using WCF services. Let's see how we can do this.
 
To start with, we will create a new WCF service and access its method in a sample web application. So our service code will look like the following:   
  1. [ServiceContract]    
  2. public interface IService1    
  3. {    
  4.     [OperationContract]    
  5.     string GetData(int value);     
  6. }    
  7.     
  8. public class Service1 : IService1    
  9. {    
  10.     public string GetData(int value)    
  11.     {    
  12.         return string.Format("You entered: {0}", value);    
  13.     }    
  14. }    
Next, we add its reference in a webproject and access the method GetData. So the code will look like the following: 

  1. ServiceReference1.Service1Client _client = new ServiceReference1.Service1Client();  
  2. var _data = _client.GetData(2); 
  3.  
Run the application and we can see the results. 
 
Now, we do not want to share the name of this method as it is. So we would like to call it something like GetMyData. For this we will add the Name property on the OperationContract attribute and specify it's value as GetMyData. So the code will look like the following:
  1.    [ServiceContract]  
  2.    public interface IService1  
  3.    {  
  4.        [OperationContract(Name="GetMyData")]  
  5.        string GetData(int value);  
  6.    }  
Now, update the service reference and see that we can no longer access the method using GetData name. We now have the name as GetMyData.
 
 
Run the application and we can see the results. Similarly, we can add the Name property on the ServiceContract, DataContract and DataMember attributes.
 
Happy coding...!!! 
 
Read more articles on WCF:

Up Next
    Ebook Download
    View all
    Learn
    View all