Web Service Optional Parameters

G

Glenn

I am writing a Web Service in C# ASP.NET 2.0 that takes two optional
parameters. One is an int and the other is a string. Below is the
definition of the Web Method:

[WebMethod]
public List<ModelFamily> ModelFamilySearch(Nullable<int> id, string name)
{
MyBusinessObject mbo = new MyBusinessObject();
return mbo.Search(id, name);

}

However, the WSDL indicates that the minOccurs="1" for the "id"
parameter. Below is a fragment of the WSDL:

<s:element name="ModelFamilySearch">
<s:complexType>
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="id" nillable="true"
type="s:int" />
<s:element minOccurs="0" maxOccurs="1" name="name"
type="s:string" />
</s:sequence>
</s:complexType>
</s:element>


Is there anyway to force the minOccurs="0" in the WSDL?

Thanks,
Glenn
 
A

Alberto Poblacion

Glenn said:
I am writing a Web Service in C# ASP.NET 2.0 that takes two optional
parameters. One is an int and the other is a string. Below is the
definition of the Web Method:

[WebMethod]
public List<ModelFamily> ModelFamilySearch(Nullable<int> id, string name)

Notice that the first parameter in this function is NOT optional. You
always have to supply the paramenter when calling the function, even if the
value that you supply is 'null'. There are no optional parameters in C#
(like in Visual Basic). The way to implement a function in C# which can be
called with different numbers of parameters is to use overloading. That is,
you would write two copies of the function like this:

public List<ModelFamily> ModelFamilySearch(string name)
{
ModelFamilySearch(null, name);
}
public List<ModelFamily> ModelFamilySearch(Nullable<int> id, string name)
{
...
}

However, you cannot expose both of them as webmethods because the standard
does not allow more than one function with the same name. You have to
specify different names in the WebMethod attribute:

[WebMethod(MessageName="ModelFamilySearch1")]
public List<ModelFamily> ModelFamilySearch(string name)
{
ModelFamilySearch(null, name);
}
[WebMethod(MessageName="ModelFamilySearch2")]
public List<ModelFamily> ModelFamilySearch(Nullable<int> id, string name)
{
...
}

Now the problem is that your client code will have to invoke the methods as
ModelFamilySearch1 and ModelFamilySearch2 depending on wether you want to
use one or two arguments. You can fix this by manually modifying the client
proxy to "realias" both calls back into an overloaded method in your client
code. But if you are going to do this, you might as well only expose the
"complete" function as a web method, and then add the overload in the client
code.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top