In this article, we will see how to overload a web method in ASP.NET Web Service. Again, this is the continuation of my previous articles of "Practical Approach To ASP.NET Web Services" series. So, we will be using the same examples again.
- Practical Approach To ASP.NET Web Services - Part One - Overview
- Practical Approach To ASP.NET Web Services - Part Two - Consuming A Web Service
- Practical Approach To ASP.NET Web Services - Part Three - Session State In A Web Service
- Practical Approach To ASP.NET Web Services - Part Four - Web Method Attribute Properties
Method overloading allows a class to have multiple methods with the same name, but with a different signature. So, in C#, methods can be overloaded based on the number, type (int,float etc), and kind (Value,Ref or Out) of parameters.
Web methods in a Web Service can also be overloaded, using MessageName property. This property is used to uniquely identify the individual XML Web service methods. So, let's understand with an example. Just flip to VS.
Here, I have made two copies of this "Add" method, both having the same names and parameters. Now, if you build the Web Service, you will get the compilation error. This means, they have to be different by number or by type.
So, I have changed the parameters of the second method, adding three numbers. Now, when you build your Web Service, there will be no errors. Now, let’s view our Web Service in the browser.
We have got an error, as shown above. But, we didn’t specify any message name which means, if we don’t specify any message name property of the web method attribute, then the name of the method will be the MessageName, by default.
So, the Web Service doesn’t know how to identify these two methods with a different MessageName.
To overload it, we need to use the MessageName property.
Now, let's view our service.
This time, we are getting a totally unrelated error. This is because when we added this Web Service to our project, Visual Studio auto-generated the Web Service binding Attribute.
VS has set it to "Basic Profiles". We need to change it to "None".
Now, let's check the service again.
We get both Add Methods but the MessageName for the second Add is "Add Two Numbers".
If you check the SOAP body.
So now, Web Service has got a way to uniquely identify these methods within the Web Service.
Note - Is it possible to overload a Web Method in a Web Service ?
Yes. The MessageName property is used to uniquely identify the individual XML Web Service methods.