Asp.Net動的呼び出しWebService
13487 ワード
Public Class WebServiceHelper
#Region "InvokeWebService"
' web
Public Shared Function InvokeWebService(ByVal url As String, ByVal methodname As String, ByVal args As Object()) As Object
Return WebServiceHelper.InvokeWebService(url, Nothing, methodname, args)
End Function
Public Shared Function InvokeWebService(ByVal url As String, ByVal classname As String, ByVal methodname As String, ByVal args As Object()) As Object
Dim [namespace] As String = "EnterpriseServerBase.WebService.DynamicWebCalling"
If (classname Is Nothing) OrElse (classname = "") Then
classname = WebServiceHelper.GetWsClassName(url.ToLower.Replace("?wsdl", ""))
End If
Try
If url.ToLower.IndexOf("?wsdl") = -1 Then
url &= "?wsdl"
End If
' WSDL
Dim wc As New WebClient()
Dim stream As Stream = wc.OpenRead(url)
Dim sd As ServiceDescription = ServiceDescription.Read(stream)
Dim sdi As New ServiceDescriptionImporter()
sdi.AddServiceDescription(sd, "", "")
Dim cn As New CodeNamespace([namespace])
'
Dim ccu As New CodeCompileUnit()
ccu.Namespaces.Add(cn)
sdi.Import(cn, ccu)
'
Dim cplist As New CompilerParameters()
cplist.GenerateExecutable = False
cplist.GenerateInMemory = True
cplist.ReferencedAssemblies.Add("System.dll")
cplist.ReferencedAssemblies.Add("System.XML.dll")
cplist.ReferencedAssemblies.Add("System.Web.Services.dll")
cplist.ReferencedAssemblies.Add("System.Data.dll")
'
Dim vbc As New VBCodeProvider
Dim cr As CompilerResults = vbc.CompileAssemblyFromDom(cplist, ccu)
If True = cr.Errors.HasErrors Then
Dim sb As New System.Text.StringBuilder()
For Each ce As System.CodeDom.Compiler.CompilerError In cr.Errors
sb.Append(ce.ToString())
sb.Append(System.Environment.NewLine)
Next
Throw New Exception(sb.ToString())
End If
' ,
Dim assembly As System.Reflection.Assembly = cr.CompiledAssembly
Dim t As Type = assembly.[GetType]([namespace] & "." & classname, True, True)
Dim obj As Object = Activator.CreateInstance(t)
Dim mi As System.Reflection.MethodInfo = t.GetMethod(methodname)
Return mi.Invoke(obj, args)
Catch ex As Exception
Throw New Exception(ex.InnerException.Message, New Exception(ex.InnerException.StackTrace))
End Try
End Function
#End Region
Private Shared Function GetWsClassName(ByVal wsUrl As String) As String
Dim parts As String() = wsUrl.Split("/"c)
Dim pps As String() = parts(parts.Length - 1).Split("."c)
Return pps(0)
End Function
End Class
呼び出し方法:
Public Function SyncResume(ByVal ResumeID As Integer) As String
Dim sResult As String = ""
Dim url As String = "http://www.webservicex.net/globalweather.asmx"
Dim args As Object() = New Object() {"beijing","China"}
sResult = WebServiceHelper.InvokeWebService(url, "GetWeather", args)
Return sResult
End Function
参照先:
動的呼び出しWebService(C#)(非常に実用的)