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.

從 .NET Core 2.0 或 Windows 10 上的 .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. 否則,此 HttpListenerHttpWebRequest 查詢將會失敗,並出現非預期的連接關閉。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

取得或設定 ExtendedProtectionPolicy,以用於工作階段的擴充保護。Gets or sets the ExtendedProtectionPolicy to use for extended protection for a session.

ExtendedProtectionSelectorDelegate

取得或設定委派,予以呼叫可決定要用於各個要求的 ExtendedProtectionPolicyGets 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

取得值,表示是否已啟動 HttpListenerGets 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 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
Start()

允許這個執行個體接收傳入要求。Allows this instance to receive incoming requests.

Stop()

使這個執行個體停止接收傳入要求。Causes this instance to stop receiving incoming requests.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

IDisposable.Dispose()

釋出這個 HttpListener 物件所持有的資源。Releases the resources held by this HttpListener object.

適用於

另請參閱