HttpListener.GetContext Método

Definição

Aguarda uma solicitação de entrada e a retorna quando recebida.

public:
 System::Net::HttpListenerContext ^ GetContext();
public System.Net.HttpListenerContext GetContext ();
member this.GetContext : unit -> System.Net.HttpListenerContext
Public Function GetContext () As HttpListenerContext

Retornos

Um objeto HttpListenerContext que representa uma solicitação do cliente.

Exceções

Falha em uma chamada de função do Win32. Verifique a propriedade ErrorCode da exceção para determinar a causa da exceção.

Esse objeto não foi iniciado ou está parado no momento.

- ou -

O HttpListener não tem nenhum prefixo URI (Uniform Resource Identifier) ao qual responder.

Este objeto está fechado.

Exemplos

O exemplo de código a seguir demonstra a chamada desse método.

// This example requires the System and System.Net namespaces.
public static void SimpleListenerExample(string[] prefixes)
{
    if (!HttpListener.IsSupported)
    {
        Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
        return;
    }
    // URI prefixes are required,
    // for example "http://contoso.com:8080/index/".
    if (prefixes == null || prefixes.Length == 0)
      throw new ArgumentException("prefixes");

    // Create a listener.
    HttpListener listener = new HttpListener();
    // Add the prefixes.
    foreach (string s in prefixes)
    {
        listener.Prefixes.Add(s);
    }
    listener.Start();
    Console.WriteLine("Listening...");
    // Note: The GetContext method blocks while waiting for a request.
    HttpListenerContext context = listener.GetContext();
    HttpListenerRequest request = context.Request;
    // Obtain a response object.
    HttpListenerResponse response = context.Response;
    // Construct a response.
    string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
    // Get a response stream and write the response to it.
    response.ContentLength64 = buffer.Length;
    System.IO.Stream output = response.OutputStream;
    output.Write(buffer,0,buffer.Length);
    // You must close the output stream.
    output.Close();
    listener.Stop();
}
Public Shared Sub SimpleListenerExample(prefixes As String())
    If Not HttpListener.IsSupported Then
        Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.")
        Return
    End If
    ' URI prefixes are required,
    ' for example "http://contoso.com:8080/index/".
    If prefixes Is Nothing Or prefixes.Length = 0 Then
        Throw New ArgumentException("prefixes")
    End If

    ' Create a listener
    Dim listener = New HttpListener()

    For Each s As String In prefixes
        listener.Prefixes.Add(s)
    Next
    listener.Start()
    Console.WriteLine("Listening...")
    ' Note: The GetContext method blocks while waiting for a request.
    Dim context As HttpListenerContext = listener.GetContext()
    Console.WriteLine("Listening...")
    ' Obtain a response object
    Dim request As HttpListenerRequest = context.Request
    ' Construct a response.
    Dim response As HttpListenerResponse = context.Response
    Dim responseString As String = "<HTML><BODY> Hello world!</BODY></HTML>"
    Dim buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(responseString)
    ' Get a response stream and write the response to it.
    response.ContentLength64 = buffer.Length
    Dim output As System.IO.Stream = response.OutputStream
    output.Write(buffer, 0, buffer.Length)
    'You must close the output stream.
    output.Close()
    listener.Stop()
End Sub

Comentários

Antes de chamar esse método, você deve chamar o Start método e adicionar pelo menos um prefixo de URI para escutar adicionando as cadeias de caracteres de URI ao HttpListenerPrefixCollection retornado pela Prefixes propriedade . Para obter uma descrição detalhada dos prefixos, consulte a visão geral da HttpListener classe.

Esse método bloqueia enquanto aguarda uma solicitação de entrada. Se você quiser que as solicitações de entrada sejam processadas de forma assíncrona (em threads separados) para que seu aplicativo não bloqueie, use o BeginGetContext método .

Notas aos Chamadores

Esse membro emite o rastreamento de informações quando você ativa o rastreamento de rede em seu aplicativo. Para obter mais informações, consulte Rastreamento de rede no .NET Framework.

Aplica-se a