Labels

Wednesday, September 26, 2007

Method Overloading in Web Services

Method Overloading in Web Services

By default Web Services do not support ‘Method Overloading’.

Reason:

When data is passed to an XML Web service it is sent in a request and when it is returned it is sent in a response. Therefore, if an XML Web service contains two or more XML Web service methods with the same name, no uniquely identification will be there. Hence it will produce error.







Solution: To resolve this, MessageName property is required to be attached to Web Method - To uniquely identify polymorphic methods.

public class Calculator : WebService

{

[WebMethod]

public int Add(int i, int j) {

return i + j;

}

[WebMethod(MessageName="Add2")]

public int Add(int i, int j, int k) {

return i + j + k;

}

}

This works perfectly well in .Net 1.x. But in .Net 2.0 this solution solves only one problem. The other problem is related to the ‘Conformity to WS-I Basic Profile v1.1’.

Reason: In .Net 2.0, by default below two attributes are added to the Web Service Class.

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService

{

}

This line indicates that your webservice conforms to the Web Services Interopability Organization's (WS-I) Baisc Profile 1.1. The Basic Profile defines a set of rules to which your webservice must conform.

One of its rules is that the webservice May Not Include Method Overloading. If you run a webservice that uses method overloading, you will receive an errormessage telling that your service is not conform to WS-I Basic Profile v1.1:

This produces below error once you have equiped the ‘Web Method’ with ‘MessageName’ property.






Solution: To resolve this error, modify the attribute as:

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.None)]

Complete Code:

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.None)]

public class Service : System.Web.Services.WebService

{

public Service () {

}

[WebMethod]

public string HelloWorld()

{

return "hello";

}

[WebMethod(MessageName = "HelloWorld2")]

public string HelloWorld(int i)

{

return "Overloading";

}

}

This will work fine as below:









Thanks & Regards,

Arun Manglick || Tech Lead

3 comments:

  1. Hello Arun,

    This information was really helpful. I had tried to overload web method in my recent project but couldn't do that and I had to use different names for methods which really does same thing.

    With the help of this article, now I can use overloading in web service.

    ReplyDelete