Compartilhar via


SoapHttpClientProtocol.Discover Método

Definição

Associa dinamicamente a um serviço Web XML descrito no documento de descoberta em Url.

public:
 void Discover();
public void Discover ();
member this.Discover : unit -> unit
Public Sub Discover ()

Exceções

A associação definida na classe do proxy não pôde ser encontrada no documento de descoberta em Url.

- ou -

A classe de proxy não tem uma associação definida.

Exemplos

O exemplo de código a seguir é uma classe proxy gerada usando o utilitário Wsdl.exe para o Math serviço Web XML. A WebServiceBindingAttribute é aplicada à classe proxy que Math define o nome MathSoap da associação e seu namespace como http://tempuri.org/.

#using <System.Web.Services.dll>
#using <System.Xml.dll>
#using <System.dll>

using namespace System::Diagnostics;
using namespace System::Xml::Serialization;
using namespace System;
using namespace System::Web::Services::Protocols;
using namespace System::Web::Services;

namespace MyMath
{

   [System::Web::Services::WebServiceBindingAttribute(Name="MathSoap",Namespace="http://tempuri.org/")]
   public ref class Math: public System::Web::Services::Protocols::SoapHttpClientProtocol
   {
   public:

      [System::Diagnostics::DebuggerStepThroughAttribute]
      Math()
      {
         this->Url = "http://www.contoso.com/math.asmx";
      }


      [System::Diagnostics::DebuggerStepThroughAttribute]
      [System::Web::Services::Protocols::SoapDocumentMethodAttribute("http://tempuri.org/Add",
      Use=System::Web::Services::Description::SoapBindingUse::Literal,
      ParameterStyle=System::Web::Services::Protocols::SoapParameterStyle::Wrapped)]
      int Add( int num1, int num2 )
      {
         array<Object^>^temp0 = {num1,num2};
         array<Object^>^results = this->Invoke( "Add", temp0 );
         return  *dynamic_cast<int^>(results[ 0 ]);
      }


      [System::Diagnostics::DebuggerStepThroughAttribute]
      System::IAsyncResult^ BeginAdd( int num1, int num2, System::AsyncCallback^ callback, Object^ asyncState )
      {
         array<Object^>^temp1 = {num1,num2};
         return this->BeginInvoke( "Add", temp1, callback, asyncState );
      }


      [System::Diagnostics::DebuggerStepThroughAttribute]
      int EndAdd( System::IAsyncResult^ asyncResult )
      {
         array<Object^>^results = this->EndInvoke( asyncResult );
         return  *dynamic_cast<int^>(results[ 0 ]);
      }

   };

}

namespace MyMath {
    using System.Diagnostics;
    using System.Xml.Serialization;
    using System;
    using System.Web.Services.Protocols;
    using System.Web.Services;

    [System.Web.Services.WebServiceBindingAttribute(Name="MathSoap", Namespace="http://tempuri.org/")]
    public class Math : System.Web.Services.Protocols.SoapHttpClientProtocol {

        [System.Diagnostics.DebuggerStepThroughAttribute()]
        public Math() {
            this.Url = "http://www.contoso.com/math.asmx";
        }

        [System.Diagnostics.DebuggerStepThroughAttribute()]
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Add", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public int Add(int num1, int num2) {
            object[] results = this.Invoke("Add", new object[] {num1,
                        num2});
            return ((int)(results[0]));
        }

        [System.Diagnostics.DebuggerStepThroughAttribute()]
        public System.IAsyncResult BeginAdd(int num1, int num2, System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("Add", new object[] {num1,
                        num2}, callback, asyncState);
        }

        [System.Diagnostics.DebuggerStepThroughAttribute()]
        public int EndAdd(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((int)(results[0]));
        }
    }
}
Namespace MyMath
    
    <System.Web.Services.WebServiceBindingAttribute(Name:="MathSoap", [Namespace]:="http://tempuri.org/")>  _
    Public Class Math
        Inherits System.Web.Services.Protocols.SoapHttpClientProtocol
        
        <System.Diagnostics.DebuggerStepThroughAttribute()>  _
        Public Sub New()
            MyBase.New
            Me.Url = "http://www.contoso.com/math.asmx"
        End Sub
        
        <System.Diagnostics.DebuggerStepThroughAttribute(),  _
         System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Add", Use:=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle:=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)>  _
        Public Function Add(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
            Dim results() As Object = Me.Invoke("Add", New Object() {num1, num2})
            Return CType(results(0),Integer)
        End Function
        
        <System.Diagnostics.DebuggerStepThroughAttribute()>  _
        Public Function BeginAdd(ByVal num1 As Integer, ByVal num2 As Integer, ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult
            Return Me.BeginInvoke("Add", New Object() {num1, num2}, callback, asyncState)
        End Function
        
        <System.Diagnostics.DebuggerStepThroughAttribute()>  _
        Public Function EndAdd(ByVal asyncResult As System.IAsyncResult) As Integer
            Dim results() As Object = Me.EndInvoke(asyncResult)
            Return CType(results(0),Integer)
        End Function
    End Class
End Namespace

O exemplo de código a seguir é um cliente do Serviço Web usando a classe proxy anterior. Dentro do EnterBtn_Click evento do Formulário Web, o cliente do serviço Web XML chama o Discover método que tenta associar dinamicamente à URL fornecida pelo usuário.

Importante

Este exemplo tem uma caixa de texto que aceita a entrada do usuário, que é uma ameaça à segurança em potencial. Por padrão, ASP.NET páginas da Web validam que a entrada do usuário não inclui elementos HTML ou script. Para obter mais informações, consulte Visão geral de explorações de script.

<%@ Page Language="C#" %>
<html>
    <script language="C#" runat="server">
       void EnterBtn_Click(Object Src, EventArgs E) 
          {
             MyMath.Math math = new MyMath.Math();
             // If the user types in a URL, attempt to dynamically bind to it.
             if (DiscoURL.Text != String.Empty)
                { 
                  math.Url = DiscoURL.Text;
                  try
                      { math.Discover();}
                  catch (Exception)
                      {
                        DiscoURL.Text = "Could not bind to MathSoap bindng at given URL.  ";
                      }
                }
 
         // Call the Add XML Web service method. 
         int total = math.Add(Convert.ToInt32(Num1.Text),Convert.ToInt32(Num2.Text));
             
             Total.Text = "Total: " + total.ToString();
         }
 
    </script>
 
    <body>
       <form action="MathClient.aspx" runat=server>
          
          Enter the URL of a disdovery document describing the MathSoap binding.
          <p> 
          <asp:textbox id="DiscoURL" runat=server Columns=80/>
          <p><p>
          Enter the two numbers you want to add and then press the Total button.
          <p>
          Number 1: <asp:textbox id="Num1" runat=server/>  +
          Number 2: <asp:textbox id="Num2" runat=server/> =
          <asp:button text="Total" Onclick="EnterBtn_Click" runat=server/>
          <p>
          <asp:label id="Total"  runat=server/>
          
       </form>
    </body>
 </html>
<%@ Page Language="VB" %>
<html>
    <script language="VB" runat="server">
    Sub EnterBtn_Click(Src As Object, E As EventArgs)
        Dim math As New Math()
        Dim result As Integer 

        ' If the user types in a URL, attempt to dynamically bind to it.
        If DiscoURL.Text <> String.Empty Then
           math.Url = DiscoURL.Text

           Try
         math.Discover()
           Catch except As Exception
          DiscoURL.Text = "Could not bind to MathSoap bindng at given URL."
           End Try       

        End If 


        ' Call to Add XML Web service method.
        result = math.Add(Convert.ToInt32(Num1.Text),Convert.ToInt32(Num2.Text))
        
        Total.Text = "Total: " & result.ToString()
    End Sub 'EnterBtn_Click
 
  </script>
 
    <body>
       <form action="MathClient.aspx" runat=server>
          
          Enter the URL of a disdovery document describing the MathSoap binding.
          <p> 
          <asp:textbox id="DiscoURL" runat=server Columns=80/>
          <p><p>
          Enter the two numbers you want to add and then press the Total button.
          <p>
          Number 1: <asp:textbox id="Num1" runat=server/>  +
          Number 2: <asp:textbox id="Num2" runat=server/> =
          <asp:button text="Total" Onclick="EnterBtn_Click" runat=server/>
          <p>
          <asp:label id="Total"  runat=server/>
          
       </form>
    </body>
 </html>

Comentários

Um cliente de serviço Web XML pode associar dinamicamente a um serviço Web XML diferente do referenciado na classe proxy usando o Discover método. Normalmente, a Url propriedade refere-se ao endereço base do serviço Web XML. No entanto, antes de invocar o Discover método, defina a Url propriedade como uma URL de um documento de descoberta. O Discover método tenta encontrar uma correspondência no documento de descoberta para a associação definida na classe proxy e, em seguida, associar dinamicamente a ela. Se tiver êxito, as chamadas de método subsequentes serão direcionadas para o serviço Web XML descrito no documento de descoberta.

Se a classe proxy for criada usando a ferramenta Linguagem de Descrição dos Serviços Web (Wsdl.exe), a classe proxy definirá a associação implementada pelos métodos de serviço Web XML invocados usando o WebServiceBindingAttribute. Quando um serviço Web XML implementa várias associações, Wsdl.exe cria uma classe proxy para cada associação. Aplicado a cada classe proxy é um WebServiceBindingAttribute que define o nome da associação e seu namespace. O documento de descoberta para o qual você definiu a Url propriedade deve conter uma referência a um serviço Web XML que implementa o mesmo nome de associação e namespace ou uma exceção é gerada.

Aplica-se a

Confira também