HttpListener 类

定义

提供一个简单的、可通过编程方式控制的 HTTP 协议侦听器。Provides a simple, programmatically controlled HTTP protocol listener. 此类不能被继承。This class cannot be inherited.

public ref class HttpListener sealed : IDisposable
public sealed class HttpListener : IDisposable
type HttpListener = class
    interface IDisposable
Public NotInheritable Class HttpListener
Implements IDisposable
继承
HttpListener
实现

示例

下面的代码示例演示如何使用 HttpListenerThe following code example demonstrates using a HttpListener.

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

注解

使用 HttpListener 类,您可以创建响应 HTTP 请求的简单 HTTP 协议侦听器。Using the HttpListener class, you can create a simple HTTP protocol listener that responds to HTTP requests. 侦听器在 HttpListener 对象的生存期内处于活动状态,并在应用程序中运行,并具有其权限。The listener is active for the lifetime of the HttpListener object and runs within your application with its permissions.

若要使用 HttpListener,请使用 HttpListener 构造函数创建类的新实例,并使用 Prefixes 属性获取对包含字符串的集合的访问权限,这些字符串指定了 HttpListener 应处理的统一资源标识符(URI)前缀。To use HttpListener, create a new instance of the class using the HttpListener constructor and use the Prefixes property to gain access to the collection that holds the strings that specify which Uniform Resource Identifier (URI) prefixes the HttpListener should process.

URI 前缀字符串由方案(http 或 https)、主机、可选端口和可选路径组成。A URI prefix string is composed of a scheme (http or https), a host, an optional port, and an optional path. http://www.contoso.com:8080/customerData/ 的完整前缀字符串的示例。An example of a complete prefix string is http://www.contoso.com:8080/customerData/. 前缀必须以正斜杠("/")结尾。Prefixes must end in a forward slash ("/"). 前缀与请求的 URI 最匹配的 HttpListener 对象将响应请求。The HttpListener object with the prefix that most closely matches a requested URI responds to the request. 多个 HttpListener 对象无法添加相同的前缀;如果 HttpListener 添加已在使用的前缀,则会引发 Win32Exception 异常。Multiple HttpListener objects cannot add the same prefix; a Win32Exception exception is thrown if a HttpListener adds a prefix that is already in use.

指定端口后,可以使用 "*" 替换主机元素,以指示如果请求的 URI 与任何其他前缀都不匹配,则 HttpListener 接受发送到端口的请求。When a port is specified, the host element can be replaced with "*" to indicate that the HttpListener accepts requests sent to the port if the requested URI does not match any other prefix. 例如,若要接收请求的 URI 未由任何 HttpListener处理时发送到端口8080的所有请求,前缀为http://*: 8080/For example, to receive all requests sent to port 8080 when the requested URI is not handled by any HttpListener, the prefix is http://*:8080/. 同样,若要指定 HttpListener 接受发送到端口的所有请求,请将主机元素替换为 "+" 字符。Similarly, to specify that the HttpListener accepts all requests sent to a port, replace the host element with the "+" character. 例如,https://+:8080For example, https://+:8080. "*" 和 "+" 字符可以出现在包含路径的前缀中。The "*" and "+" characters can be present in prefixes that include paths.

从 Windows 10 上的 .NET Core 2.0 或 .NET Framework 4.6 开始,由 HttpListener 对象管理的 URI 前缀支持通配符子域。Starting with .NET Core 2.0 or .NET Framework 4.6 on Windows 10, wildcard subdomains are supported in URI prefixes that are managed by an HttpListener object. 若要指定通配符子域,请在 URI 前缀中将 "*" 字符用作主机名的一部分。To specify a wildcard subdomain, use the "*" character as part of the hostname in a URI prefix. 例如, http://*. foo.com/For example, http://*.foo.com/. 将此作为参数传递给 Add 方法。Pass this as the argument to the Add method. 这适用于 Windows 10 上的 .NET Core 2.0 或 .NET Framework 4.6;在早期版本中,这将生成 HttpListenerExceptionThis works as of .NET Core 2.0 or .NET Framework 4.6 on Windows 10; in earlier versions, this generates an HttpListenerException.

警告

应使用顶级通配符绑定(http://*: 8080/http://+:8080)。Top-level wildcard bindings (http://*:8080/ and http://+:8080) should not be used. 顶级通配符绑定可能会为应用带来安全漏洞。Top-level wildcard bindings can open up your app to security vulnerabilities. 此行为同时适用于强通配符和弱通配符。This applies to both strong and weak wildcards. 使用显式主机名而不是通配符。Use explicit host names rather than wildcards. 如果可控制整个父域(区别于易受攻击的 *.com),则子域通配符绑定(例如,*.mysub.com)不具有此安全风险。Subdomain wildcard binding (for example, *.mysub.com) doesn't have this security risk if you control the entire parent domain (as opposed to *.com, which is vulnerable). 有关详细信息,请参阅 rfc7230 第 5.4 条See rfc7230 section-5.4 for more information.

若要开始侦听来自客户端的请求,请将 URI 前缀添加到集合,并调用 Start 方法。To begin listening for requests from clients, add the URI prefixes to the collection and call the Start method. HttpListener 提供同步和异步模型来处理客户端请求。HttpListener offers both synchronous and asynchronous models for processing client requests. 请求及其关联的响应使用 GetContext 方法或其异步对应方法(BeginGetContextEndGetContext 方法)返回的 HttpListenerContext 对象进行访问。Requests and their associated responses are accessed using the HttpListenerContext object returned by the GetContext method or its asynchronous counterparts, the BeginGetContext and EndGetContext methods.

如果你的应用程序应在等待客户端请求时被阻止,并且你希望一次只处理一个请求,则可以使用同步模型。The synchronous model is appropriate if your application should block while waiting for a client request and if you want to process only one request at a time. 使用同步模型,调用 GetContext 方法,该方法将等待客户端发送请求。Using the synchronous model, call the GetContext method, which waits for a client to send a request. 方法返回 HttpListenerContext 对象,以便在发生一次处理时进行处理。The method returns an HttpListenerContext object to you for processing when one occurs.

在更复杂的异步模型中,你的应用程序不会在等待请求时被阻止,并且每个请求会在其自己的执行线程中进行处理。In the more complex asynchronous model, your application does not block while waiting for requests and each request is processed in its own execution thread. 使用 BeginGetContext 方法指定要为每个传入请求调用的应用程序定义的方法。Use the BeginGetContext method to specify an application-defined method to be called for each incoming request. 在该方法中,调用 EndGetContext 方法获取请求,处理请求并做出响应。Within that method, call the EndGetContext method to obtain the request, process it, and respond.

在这两种模型中,均使用 HttpListenerContext.Request 属性访问传入请求,并由 HttpListenerRequest 对象表示。In either model, incoming requests are accessed using the HttpListenerContext.Request property and are represented by HttpListenerRequest objects. 同样,使用 HttpListenerContext.Response 属性访问响应,并由 HttpListenerResponse 对象表示。Similarly, responses are accessed using the HttpListenerContext.Response property and are represented by HttpListenerResponse objects. 这些对象与 HttpWebRequestHttpWebResponse 对象共享某些功能,但后面的对象不能与 HttpListener 结合使用,因为它们实现客户端,而不是服务器和行为。These objects share some functionality with the HttpWebRequest and HttpWebResponse objects, but the latter objects cannot be used in conjunction with HttpListener because they implement client, not server, behaviors.

HttpListener 可能需要客户端身份验证。An HttpListener can require client authentication. 可以指定用于身份验证的特定方案,也可以指定一个委托来确定要使用的方案。You can either specify a particular scheme to use for authentication, or you can specify a delegate that determines the scheme to use. 您必须需要某种形式的身份验证才能获取有关客户端标识的信息。You must require some form of authentication to obtain information about the client's identity. 有关其他信息,请参阅 UserAuthenticationSchemesAuthenticationSchemeSelectorDelegate 属性。For additional information, see the User, AuthenticationSchemes, and AuthenticationSchemeSelectorDelegate properties.

备注

如果使用 https 创建 HttpListener,则必须为该侦听器选择服务器证书。If you create an HttpListener using https, you must select a Server Certificate for that listener. 否则,此 HttpListener HttpWebRequest 查询将失败,并出现意外的连接关闭。Otherwise, an HttpWebRequest query of this HttpListener will fail with an unexpected close of the connection.

备注

您可以使用 Network Shell (netsh)配置服务器证书和其他侦听器选项。You can configure Server Certificates and other listener options by using Network Shell (netsh.exe). 有关更多详细信息,请参阅Network Shell (Netsh)See Network Shell (Netsh) for more details. 可执行文件开始随 Windows Server 2008 和 Windows Vista 一起发布。The executable began shipping with Windows Server 2008 and Windows Vista.

备注

如果为 HttpListener指定多个身份验证方案,则侦听器将按以下顺序质询客户端: NegotiateNTLMDigest,然后 BasicIf you specify multiple authentication schemes for the HttpListener, the listener will challenge clients in the following order: Negotiate, NTLM, Digest, and then Basic.

HTTP.sysHTTP.sys

HttpListener 类是在 HTTP.sys之上构建的,后者是处理 Windows 的所有 HTTP 流量的内核模式侦听器。The HttpListener class is built on top of HTTP.sys, which is the kernel mode listener that handles all HTTP traffic for Windows. HTTP.sys 提供连接管理、带宽限制和 web 服务器日志记录。HTTP.sys provides connection management, bandwidth throttling, and web server logging. 使用httpcfg.exe工具来添加 SSL 证书。Use the HttpCfg.exe tool to add SSL certificates.

构造函数

HttpListener()

初始化 HttpListener 类的新实例。Initializes a new instance of the HttpListener class.

属性

AuthenticationSchemes

获取或设置用于客户端身份验证的方案。Gets or sets the scheme used to authenticate clients.

AuthenticationSchemeSelectorDelegate

获取或设置一个委托,调用它来确定用于客户端身份验证的协议。Gets or sets the delegate called to determine the protocol used to authenticate clients.

DefaultServiceNames

获取由已注册前缀确定的服务提供程序名 (SPN) 的默认列表。Gets a default list of Service Provider Names (SPNs) as determined by registered prefixes.

ExtendedProtectionPolicy

获取或设置用于会话的扩展保护的 ExtendedProtectionPolicyGets or sets the ExtendedProtectionPolicy to use for extended protection for a session.

ExtendedProtectionSelectorDelegate

获取或设置在确定要用于每个请求的 ExtendedProtectionPolicy 时调用的委托。Gets or sets the delegate called to determine the ExtendedProtectionPolicy to use for each request.

IgnoreWriteExceptions

获取或设置 Boolean 值,该值指定应用程序是否接收 HttpListener 向客户端发送响应时发生的异常。Gets or sets a Boolean value that specifies whether your application receives exceptions that occur when an HttpListener sends the response to the client.

IsListening

获取一个值,指示 HttpListener 是否已启动。Gets a value that indicates whether HttpListener has been started.

IsSupported

获取一个值,指示 HttpListener 是否可用于当前操作系统。Gets a value that indicates whether HttpListener can be used with the current operating system.

Prefixes

获取由此 HttpListener 对象处理的统一资源标识符 (URI) 前缀。Gets the Uniform Resource Identifier (URI) prefixes handled by this HttpListener object.

Realm

获取或设置与此 HttpListener 对象关联的领域或资源分区。Gets or sets the realm, or resource partition, associated with this HttpListener object.

TimeoutManager

HttpListener 实例的超时管理器。The timeout manager for this HttpListener instance.

UnsafeConnectionNtlmAuthentication

获取或设置 Boolean 值,该值控制当使用 NTLM 时是否需要对使用同一传输控制协议 (TCP) 连接的其他请求进行身份验证。Gets or sets a Boolean value that controls whether, when NTLM is used, additional requests using the same Transmission Control Protocol (TCP) connection are required to authenticate.

方法

Abort()

立刻关闭 HttpListener 对象,这样会放弃所有当前排队的请求。Shuts down the HttpListener object immediately, discarding all currently queued requests.

BeginGetContext(AsyncCallback, Object)

开始异步检索传入的请求。Begins asynchronously retrieving an incoming request.

Close()

关闭 HttpListenerShuts down the HttpListener.

EndGetContext(IAsyncResult)

完成检索传入的客户端请求的异步操作。Completes an asynchronous operation to retrieve an incoming client request.

Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetContext()

等待传入的请求,接收到请求时返回。Waits for an incoming request and returns when one is received.

GetContextAsync()

等待传入请求以作为异步操作。Waits for an incoming request as an asynchronous operation.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
Start()

允许此实例接收传入的请求。Allows this instance to receive incoming requests.

Stop()

使此实例停止接收新的传入请求,并终止处理所有正在进行的请求。Causes this instance to stop receiving new incoming requests and terminates processing of all ongoing requests.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

显式接口实现

IDisposable.Dispose()

释放此 HttpListener 对象持有的资源。Releases the resources held by this HttpListener object.

适用于

另请参阅