65.9K
CodeProject 正在变化。 阅读更多。
Home

在不添加 Web 引用时调用 Web 服务

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (9投票s)

2009 年 9 月 11 日

CPOL
viewsIcon

108519

在不添加 Web 引用时调用 Web 服务。

引言

客户要求,由于某种原因他无法添加 Web 引用,希望能在 web.config 文件中指定 Web 服务 URL,或者直接硬编码。因此,这是我的第一篇文章:)

背景

我创建这个资源已经一年多时间了。我通过互联网获取了相关信息/想法。

我从 我的博客 复制而来。

Using the Code

  1. 创建一个名为 "DynamicWebService" 的类,并创建一个名为 "CallWebService" 的新方法。
  2. 创建该类的对象,并使用 Web 服务 URL 和其他参数调用 "CallWebService" 方法。
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.Security.Permissions
Imports System.Web.Services.Description
Imports System.Reflection

Public Function CallWebService(ByVal webServiceAsmxUrl As String, _
       ByVal serviceName As String, ByVal methodName As String, _
       ByVal args() As Object) As Object

    Try
    Dim client As System.Net.WebClient = New System.Net.WebClient()

    '-Connect To the web service
    Dim stream As System.IO.Stream = _
        client.OpenRead(webServiceAsmxUrl + "?wsdl")

    'Read the WSDL file describing a service.
    Dim description As ServiceDescription = ServiceDescription.Read(stream)

    'LOAD THE DOM'''''''''''''''''''''''''''

    '--Initialize a service description importer.
    Dim importer As ServiceDescriptionImporter = New ServiceDescriptionImporter()
    importer.ProtocolName = "Soap12" ' Use SOAP 1.2.
    importer.AddServiceDescription(description, Nothing, Nothing)

    '--Generate a proxy client. 

    importer.Style = ServiceDescriptionImportStyle.Client
    '--Generate properties to represent primitive values.
    importer.CodeGenerationOptions = _
         System.Xml.Serialization.CodeGenerationOptions.GenerateProperties

    'Initialize a Code-DOM tree into which we will import the service.
    Dim nmspace As CodeNamespace = New CodeNamespace()
    Dim unit1 As CodeCompileUnit = New CodeCompileUnit()
    unit1.Namespaces.Add(nmspace)

    'Import the service into the Code-DOM tree. 
    'This creates proxy code that uses the service.

    Dim warning As ServiceDescriptionImportWarnings = _
                   importer.Import(nmspace, unit1)

    If warning = 0 Then

            '--Generate the proxy code
            Dim provider1 As CodeDomProvider = _
                      CodeDomProvider.CreateProvider("VB")
            '--Compile the assembly proxy with the // appropriate references
            Dim assemblyReferences() As String
            assemblyReferences = New String() {"System.dll", _
                "System.Web.Services.dll", "System.Web.dll", _
                "System.Xml.dll", "System.Data.dll"}
        	Dim parms As CompilerParameters = New CompilerParameters(assemblyReferences)
	parms.GenerateInMemory = True '(Thanks for this line nikolas)
        	Dim results As CompilerResults = provider1.CompileAssemblyFromDom(parms, unit1)

        '-Check For Errors
        If results.Errors.Count > 0 Then

            Dim oops As CompilerError
            For Each oops In results.Errors
                System.Diagnostics.Debug.WriteLine("========Compiler error============")
                System.Diagnostics.Debug.WriteLine(oops.ErrorText)
            Next
            Throw New System.Exception("Compile Error Occurred calling webservice.")
        End If

        '--Finally, Invoke the web service method
        Dim wsvcClass As Object = results.CompiledAssembly.CreateInstance(serviceName)
        Dim mi As MethodInfo = wsvcClass.GetType().GetMethod(methodName)
        Return mi.Invoke(wsvcClass, args)

    Else
        Return Nothing
    End If

    Catch ex As Exception
    Throw ex
    End Try
End Function

调用

在 WebForm 或 Windows Form 或方法等中调用此 Web 服务,如下所示

    Dim WebserviceUrl As String = _
	"http://www.abc.com/lgl/test/webservice/v1_00/security.asmx"

    'specify service name
    Dim serviceName As String = "SecurityAndSessionManagement"

    'specify method name to be called
    Dim methodName As String = "Session_Start"

    'Arguments passed to the method
    Dim arArguments(1) As String
    arArguments(0) = "abc"
    arArguments(1) = "xxxx"

    Dim objCallWS As New DynamicWebService
    sSessionID = objCallWS.CallWebService(WebserviceUrl, serviceName, _
                                          methodName, arArguments)
    MsgBox("new SessionID: " & sSessionID)

历史

  • 2009 年 9 月 11 日:初始发布
无需添加 Web 引用即可调用 Web 服务 - CodeProject - 代码之家
© . All rights reserved.