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:
- [ServiceContract]
- public interface IService1
- {
- [OperationContract]
- string GetData(int value);
- }
-
- public class Service1 : IService1
- {
- public string GetData(int value)
- {
- return string.Format("You entered: {0}", value);
- }
- }
Next, we add its reference in a webproject and access the method GetData. So the code will look like the following:
- ServiceReference1.Service1Client _client = new ServiceReference1.Service1Client();
- var _data = _client.GetData(2);
-
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:
- [ServiceContract]
- public interface IService1
- {
- [OperationContract(Name="GetMyData")]
- string GetData(int value);
- }
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: