3

I'm building a web API using web service. Users may use it like this: http://www.example.com/example.asmx/hello?param1=str&param2=str

or:

http://www.example.com/example.asmx/hello?param1=str .

I want to make param1 required while param2 optional.But my code below always throws an exception that says missing values for parameters when I try to call http://www.example.com/example.asmx/hello?param1=str. It works fine with http://www.example.com/example.asmx/hello?param1=str&param2=str.

[WebMethod]
public string hello(int param1, int param2 = 0)
{
    return "hello!";
}

Is there any way to fix it? If not, what techniques can I use to build a web API that accept optional parameters which is very common in public APIs. I'm a newbie so I don't know if web service is a good choice for building web APIs. Any help is appreciated.

4

3 回答 3

3

基本上你不能那样做。

我建议你先阅读这篇文章:http: //blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx

它很好地解释了参数是如何绑定的。

于 2013-05-27T15:08:54.613 回答
0

您是否考虑过使用在应用程序(wpf / winforms)中工作的参数。

    // not tested
    [WebMethod]
    public string hello(params int[] list)
    {
        string s = "Hello\n";
        // do some stuff with your ints
        for ( int i = 0 ; i < list.Length ; i++ )
          s += list[i] + "\n" ;

        return s;
    }
于 2013-05-27T16:06:43.727 回答
0

问题可能是对于 web 方法,此参数是必需的。也许这会有所帮助。

按照MinOccurs Attribute Binding SupportDefault Attribute Binding Support

  1. 带有公共布尔字段的值类型,该字段使用前面在将 XSD 转换为源中描述的指定命名约定 - 输出<element>元素 0 的 minOccurs 值。

    [WebMethod]
    public SomeResult SomeMethod(bool optionalParam, [XmlIgnore] bool optionalParamSpecified)
    结果:
    <s:element minOccurs="0" maxOccurs="1" name="optionalParam" type="s:boolean" />

  2. 具有通过 System.Component.DefaultValueAttribute 指定的默认值的值类型 - 输出<element>元素 0 的 minOccurs 值。在<element>元素中,默认值也通过默认 XML 属性指定。

    [WebMethod]
    public SomeResult SomeMethod([DefaultValue(true)] bool optionalParam)
    结果:
    <s:element minOccurs="0" maxOccurs="1" default="true" name="optionalParam" type="s:boolean" />

于 2017-12-13T01:39:41.753 回答