HttpListenerPrefixCollection.Add(String) Método

Definición

Agrega un prefijo del identificador uniforme de recursos (URI) a la colección.

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

String que identifica la información de URI que se compara en las solicitudes entrantes. El prefijo debe terminar con una barra diagonal ("/").

Implementaciones

Excepciones

uriPrefix es null.

uriPrefix no utiliza el esquema http:// o https://. Estos son los únicos esquemas admitidos en los objetos HttpListener.

O bien uriPrefix no es un prefijo URI con formato correcto. Asegúrese de que la cadena finaliza con un "/".

La clase HttpListener asociada a esta colección está cerrada.

Error al llamar a una función de Windows. Examine la propiedad ErrorCode de la excepción para determinar su causa. Se produce esta excepción si otro objeto HttpListener ya ha agregado el prefijo uriPrefix.

Ejemplos

En el ejemplo de código siguiente se crea un HttpListener y se agregan prefijos especificados por el usuario a su 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

Comentarios

Este método agrega un prefijo de URI al conjunto de prefijos administrados por el objeto asociado HttpListener . Al comprobar uriPrefix para asegurarse de que es válido, se omiten las mayúsculas y minúsculas.

Una cadena de prefijo de URI se compone de un esquema (http o https), un host, un puerto opcional y una ruta de acceso opcional, por ejemplo, "http://www.contoso.com:8080/customerData/". El prefijo debe terminar con una barra diagonal ("/"). con HttpListener el prefijo que coincide más estrechamente con un URI solicitado responde a la solicitud. Varios HttpListener objetos no pueden agregar el mismo prefijo. Se produce una HttpListenerException excepción si HttpListener agrega un prefijo que ya está en uso.

Cuando se especifica un puerto, el elemento host se puede reemplazar por "*" para indicar que HttpListener acepta las solicitudes enviadas al puerto si el URI solicitado no coincide con ningún otro prefijo. Por ejemplo, para recibir todas las solicitudes enviadas al puerto 8080 cuando el URI solicitado no se controla mediante ningún otro HttpListener, el prefijo es "http://*:8080/". Del mismo modo, para especificar que HttpListener acepta todas las solicitudes enviadas a un puerto, reemplace el elemento host por el carácter "+", "https://+:8080/". Los caracteres "" y "*``+" pueden estar presentes en prefijos que incluyen rutas de acceso.

A partir de .NET 4.5.3 y Windows 10, los subdominios comodín se admiten en prefijos de URI administrados por un HttpListener objeto. Para especificar un subdominio de caracteres comodín, use el carácter "*" como parte del nombre de host en un prefijo URI: por ejemplo, http://*.foo.com/, y páselo como argumento al método HttpListenerPrefixCollection.Add. Esto funcionará en .NET 4.5.3 y Windows 10; en versiones anteriores, esto generaría unaHttpListenerException

Se aplica a

Consulte también