旧主题但有一点扭曲 - 我搜索过但无法找到答案。
我知道我不能使用带有web方法的默认值的可选参数,所以我必须使用函数重载但是......我看到一个可选参数的例子,我有大约10个!
如果我理解3个可选参数,我将需要7个重载函数(3个用于1个参数,3个用于2个,1个用于整个3个)所以我需要多少10个?很多!必须有更好的方法,不是吗?并且请不要告诉我使用WCF - 我现在无法切换到那个并且我必须使用WSDL
非常感谢帮助
答案 0 :(得分:3)
您可以只传递具有默认值属性的Object(Class),而不是使用许多可选参数。这样它可以像可选参数一样工作:
Public Class Parameters
Public Property Name As String = "Undefined"
Public Property Country as string = "United Kingdom"
End Class
定义您的WebMethod以接受此对象类型
Public Function WebMethod(prm as Parameters)
用法:
使用名称传递参数:
WebMethod(New Parameters With {.Name = "Jane"})
使用名称和国家/地区传递参数:
WebMethod(New Parameters With {.Name = "Amr", .Country = "Egypt"})
仅使用国家/地区传递参数:
WebMethod(New Parameters With {.Country = "China"})
答案 1 :(得分:1)
您可以将变量声明为Nullable (of <your type>)
,只需要一个包含所有10个参数的Web服务
这是您的Webmethod,只有2个可选参数,但您可以轻松地将其扩展为10:
<WebMethod(Description:="TEST1")> _
Public Function TEST1(<XmlElement()> param1 As Nullable(Of Double), <XmlElement()> param2 As Nullable(Of Double)) As <XmlElement()> Double
Try
Dim result As Double = 0
If Not param1 Is Nothing Then
result += param1
End If
If Not param2 Is Nothing Then
result += param2
End If
Return result
Catch ex As Exception
End Try
Return 0
End Function
此SoapUI调用:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:not="http://mysite.org/">
<soapenv:Header/>
<soapenv:Body>
<not:TEST1>
<not:param1>1</not:param1>
<not:param2>2</not:param2>
</not:TEST1>
</soapenv:Body>
</soapenv:Envelope>
结果如下:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<TEST1Response xmlns="http://mysite.org/">
<TEST1Result>3</TEST1Result>
</TEST1Response>
</soap:Body>
</soap:Envelope>
此SoapUI调用:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:not="http://mysite.org/">
<soapenv:Header/>
<soapenv:Body>
<not:TEST1>
<not:param1>1</not:param1>
</not:TEST1>
</soapenv:Body>
</soapenv:Envelope>
结果如下:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<TEST1Response xmlns="http://mysite.org/">
<TEST1Result>1</TEST1Result>
</TEST1Response>
</soap:Body>
</soap:Envelope>
在此示例中, Nullable (of Double)
这两个参数都是可选的。