27

Possible Duplicate:
Can I have an optional parameter for an ASP.NET SOAP web service

I have tried looking around for this but I really cannot find the right solution for what I want to do. Sorry for the repetition since I know this has been asked before. I have a Web Service Method in which I want to have an optional parameter such as:

public void MyMethod(int a, int b, int c = -3)

I already know I cannot use nullable parameters, so I am just trying to use a default value. Problem is when I call this method without supplying argument c is still get an exception. Is there somewhere I have to specify it is in fact optional?

Thanksю

Community
  • 1
  • 1
Steve Kiss
  • 1,108
  • 3
  • 13
  • 24

3 Answers3

30

You can achieve optional parameters by overloads and using the MessageName property.

[WebMethod(MessageName = "MyMethodDefault")]
public void MyMethod(int a, int b)
{
      MyMethod( a, b, -3);
}

[WebMethod(MessageName = "MyMethod")]
public void MyMethod(int a, int b, int c)

For this to work, you may also need to change

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 

to

[WebServiceBinding(ConformsTo = WsiProfiles.None)] 

if you haven't done so already, as WS-I Basic Profile v1.1 does not allow overloads

Inspector Squirrel
  • 2,548
  • 2
  • 27
  • 38
Markis
  • 1,703
  • 15
  • 14
  • 7
    To make this work, you may also need to change [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] to [WebServiceBinding(ConformsTo = WsiProfiles.None)] as WS-I Basic Profile v1.1 does not allow overloads – ShibbyUK Aug 21 '15 at 08:45
  • I have a perfect solution here https://stackoverflow.com/a/71273352/3715484 – Mohsin Feb 26 '22 at 01:24
10

Use methods overloading:

[WebMethod(MessageName = "MyMethod1")]
public void MyMethod(int a, int b)
{
    return MyMethod(a, b, -3);
}

[WebMethod(MessageName = "MyMethod2")]
public void MyMethod(int a, int b, int c)
{
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
3

I've looked into optional parameters etc. before, and straight asmx web services don't support this (with default generated WSDLs). With WCF however, you can mark parameters in your datacontract as IsRequired=false - see Optional parameters in ASP.NET web service

Community
  • 1
  • 1
Chris Pont
  • 789
  • 5
  • 14