HttpListenerPrefixCollection.Add(String) Método

Definição

Adiciona um prefixo de URI (Uniform Resource Identifier) à coleção.

public:
 virtual void Add(System::String ^ uriPrefix);
public void Add (string uriPrefix);
abstract member Add : string -> unit
override this.Add : string -> unit
Public Sub Add (uriPrefix As String)

Parâmetros

uriPrefix
String

Um String que identifica as informações de URI que são comparadas em solicitações de entrada. O prefixo deve terminar com uma barra "/".

Implementações

Exceções

uriPrefix é null.

uriPrefix não usa o esquema http:// ou https://. Esses são os únicos esquemas com suporte para objetos HttpListener.

- ou - uriPrefix não é um prefixo URI formatado corretamente. Verifique se a cadeia de caracteres termina com um "/".

O HttpListener associado a esta coleção está fechado.

Falha de uma chamada de função do Windows. Verifique a propriedade ErrorCode da exceção para determinar a causa da exceção. Essa exceção será lançada se outro HttpListener já tiver adicionado o prefixo uriPrefix.

Exemplos

O exemplo de código a seguir cria um HttpListener e adiciona prefixos especificados pelo usuário ao seu HttpListenerPrefixCollection.

// 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

Esse método adiciona um prefixo de URI ao conjunto de prefixos gerenciados pelo objeto associado HttpListener . Ao verificar uriPrefix se ela é válida, o caso é ignorado.

Uma cadeia de caracteres de prefixo URI é composta por um esquema (http ou https), um host, uma porta opcional e um caminho opcional, por exemplo, "http://www.contoso.com:8080/customerData/". O prefixo deve terminar com uma barra "/". O HttpListener prefixo que corresponde mais de perto a um URI solicitado responde à solicitação. Vários HttpListener objetos não podem adicionar o mesmo prefixo. Uma HttpListenerException exceção será gerada se um HttpListener prefixo adicionar que já esteja em uso.

Quando uma porta é especificada, o elemento host pode ser substituído por "*" para indicar que as HttpListener solicitações de aceitação enviadas à porta se o URI solicitado não corresponder a nenhum outro prefixo. Por exemplo, para receber todas as solicitações enviadas para a porta 8080 quando o URI solicitado não for tratado por nenhum outro HttpListener, o prefixo é "http://*:8080/". Da mesma forma, para especificar que aceita HttpListener todas as solicitações enviadas a uma porta, substitua o elemento host pelo caractere "+" "https://+:8080/". Os caracteres "*" e "+" podem estar presentes em prefixos que incluem caminhos.

A partir do .NET 4.5.3 e Windows 10, há suporte para subdomínios curinga em prefixos de URI gerenciados por um HttpListener objeto. Para especificar um subdomínio curinga, use o caractere "*" como parte do nome do host em um prefixo de URI: por exemplo, http://*.foo.com/e passe-o como o argumento para o método HttpListenerPrefixCollection.Add. Isso funcionará no .NET 4.5.3 e Windows 10; em versões anteriores, isso geraria umHttpListenerException

Aplica-se a

Confira também