HttpListener HttpListener HttpListener HttpListener Class

定义

提供一个简单的、可通过编程方式控制的 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
继承
HttpListenerHttpListenerHttpListenerHttpListener
实现

示例

下面的代码示例演示了如何使用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();
}

注解

使用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属性来访问集合,它包含指定的统一资源标识符 (URI) 的字符串前缀HttpListener应处理。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 ("/"). HttpListener具有最为匹配请求的 URI 前缀对象响应请求。The HttpListener object with the prefix that most closely matches a requested URI responds to the request. 多个HttpListener对象不能添加相同的前缀;Win32Exception如果引发异常HttpListener添加前缀已被使用。Multiple HttpListener objects cannot add the same prefix; a Win32Exception exception is thrown if a HttpListener adds a prefix that is already in use.

指定端口,主机元素可以被替换为"*"以指示HttpListener接受请求发送到端口,如果请求的 URI 与任何其他前缀不匹配。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. 例如,若要接收的所有请求发送到端口 8080 时任何未处理请求的 URI HttpListener,该前缀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.

从.NET Core 2.0 或 Windows 10 上的.NET Framework 4.6 开始,在 URI 的前缀中受支持通配符子域HttpListener对象。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. 这适用于自.NET Core 2.0 或 Windows 10; 上的.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. 使用访问请求和其关联的响应HttpListenerContext返回的对象GetContext方法或其异步对应BeginGetContextEndGetContext方法。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. 有关其他信息,请参阅UserAuthenticationSchemes,和AuthenticationSchemeSelectorDelegate属性。For additional information, see the User, AuthenticationSchemes, and AuthenticationSchemeSelectorDelegate properties.

备注

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

备注

可以使用 Network Shell (netsh.exe) 来配置服务器证书和其他侦听器选项。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.

构造函数

HttpListener() HttpListener() HttpListener() HttpListener()

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

属性

AuthenticationSchemes AuthenticationSchemes AuthenticationSchemes AuthenticationSchemes

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

AuthenticationSchemeSelectorDelegate AuthenticationSchemeSelectorDelegate AuthenticationSchemeSelectorDelegate AuthenticationSchemeSelectorDelegate

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

DefaultServiceNames DefaultServiceNames DefaultServiceNames DefaultServiceNames

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

ExtendedProtectionPolicy ExtendedProtectionPolicy ExtendedProtectionPolicy ExtendedProtectionPolicy

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

ExtendedProtectionSelectorDelegate ExtendedProtectionSelectorDelegate ExtendedProtectionSelectorDelegate ExtendedProtectionSelectorDelegate

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

IgnoreWriteExceptions IgnoreWriteExceptions IgnoreWriteExceptions 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 IsListening IsListening IsListening

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

IsSupported IsSupported IsSupported IsSupported

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

Prefixes Prefixes Prefixes Prefixes

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

Realm Realm Realm Realm

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

TimeoutManager TimeoutManager TimeoutManager TimeoutManager

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

UnsafeConnectionNtlmAuthentication UnsafeConnectionNtlmAuthentication UnsafeConnectionNtlmAuthentication 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() Abort() Abort() Abort()

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

BeginGetContext(AsyncCallback, Object) BeginGetContext(AsyncCallback, Object) BeginGetContext(AsyncCallback, Object) BeginGetContext(AsyncCallback, Object)

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

Close() Close() Close() Close()

关闭 HttpListenerShuts down the HttpListener.

EndGetContext(IAsyncResult) EndGetContext(IAsyncResult) EndGetContext(IAsyncResult) EndGetContext(IAsyncResult)

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

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
GetContext() GetContext() GetContext() GetContext()

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

GetContextAsync() GetContextAsync() GetContextAsync() GetContextAsync()

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

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
Start() Start() Start() Start()

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

Stop() Stop() Stop() Stop()

使此实例停止接收传入的请求。Causes this instance to stop receiving incoming requests.

ToString() ToString() ToString() ToString()

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

(Inherited from Object)

显式界面实现

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

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

适用于

另请参阅