Introduction
Web services are also classes just like any other .NET classes. However, they typically have methods that are marked as web methods. In addition to web methods they can also contain normal methods.
Since a web service is a class it can utilize all the OO features like method overloading. In this article and demo we will see how to use method overloading in a web service.
Creating web methods
We will create a simple web service that has following three overloaded methods :
- Public Function GetWelcomeMessage() As String
- Public Function GetWelcomeMessage(ByVal name As String) As String
- Public Function GetWelcomeMessage(ByVal name As String, ByVal dob As DateTime) As String
All the three methods return variants of a welcome message to the web service client. Next, we will mark two methods as web methods but keep last method as normal method of the class. To mark the methods as web methods just use following syntax :
VB.NET
<WebMethod()>
Public Function GetWelcomeMessage() As String
C#
[WebMethod()]
public string GetWelcomeMessage()
{...}
Compile the class and run it in the browser (I assume that you are using VS.NET). You should get a error saying that GetWelcomeMessage method must be marked with MessageName attribute. This is because even though our class can distinction between overloaded methods when we call them over SOAP there should be some unique identification for each one.
Adding MessageName attribute
To overcome the problem we will add MessageName attribute to the second web method as shown below :
VB.NET
<WebMethod(MessageName:="GetWelcomeMessageWithName")>
Public Function GetWelcomeMessage(ByVal name As String) As String
C#
[WebMethod(MessageName="GetWelcomeMessageWithName")]
Public Function GetWelcomeMessage(ByVal name As String) As String
Now, compile the service again and run in the browser. You will notice that you get GetWelcomeMessageWithName listed rather than GetWelcomeMessage for the second web method. In all your client code you will use this method name instead of original method name. Your typical client code will look like this :
'I assume that you have created web service proxy
'either by WSDL utility or adding a web reference
'in VS.NET
Dim x as new MyWebServices.Service1()
'call first web method
dim str1 as string=x.GetWelcomeMessage()
'now call overloaded version
dim str2 as string=x.GetWelcomeMessageWithName()
Note that in VB.NET MessageName attribute is represented by 'named argument'.
The third method is not marked as a web method and hence can be used just like any overloaded method inside the web service class.