Technology with opinion

Friday, September 02, 2005

Overloading Web Service Methods in .Net

A largely misunderstood issue in .Net web services is the capability of overloading web service methods. Overloading web service methods is possible and very easy but it helps to have some understanding of SOAP first.

If you navigate to your web service and click the link "Service Description", or just add ?WSDL onto the end of your web service within your browser, example:

http://localhost/MyWebServices/WebService1.asmx?WSDL

You will see the Web Service Description Layer (WSDL). Inside your WSDL you will see your web service methods represented as operations such as:

<wsdl:operation name="Add">
...
</wsdl:operation>

Now if you go into your Add method inside .Net and add try to overload it, the problem you have is that method names within .Net map to both operations and message elements within your WSDL and you cannot have two message names that are the same, example:

<wsdl:message name="AddSoapIn">
<wsdl:message name="AddSoapIn">

Cannot exist twice. The fix is simple, add a WebMethod attribute to both methods and make sure they have distinct names between them.

[WebMethod(MessageName="Add_TwoNumbers")]
public int Add(int x, int y)
{
return x + y;
}

[WebMethod(MessageName="Add_ThreeNumbers")]
public int Add(int x, int y, int z)
{
return x + y + z;
}

Now your WSDL will have message elements with names:
Add_TwoNumbersSoapIn
Add_TwoNumbersSoapOut
Add_ThreeNumbersSoapIn
Add_ThreeNumbersSoapOut

But your operations (within WSDL) will have the following:
<wsdl:operation name="Add">
<wsdl:operation name="Add">

Thus when you generate your proxy class for your web service (IE: Web Reference, or WSDL.exe) then you can open your proxy class and see how it maps overloaded methods to the operations properly.

While it's not necessary to rewrite the WSDL yourself, understanding how to manipulate the WSDL through attributes within your .Net web service is invaluable.

See Also: WSDL spec from the W3C

2 comments:

Unknown said...

It is absolutely right about Method overloading. But my doubt is About Operator over loading in web Services

sekhar said...

THis code is not working properly for me.