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();
}
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屬性來存取集合,其中保存字串,其中指定的統一資源識別元 (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因為它們實作用戶端不、 server 行為。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.

注意

您可以使用網路殼層 (netsh.exe),來設定伺服器憑證和其他接聽程式選項。You can configure Server Certificates and other listener options by using Network Shell (netsh.exe). 請參閱網路殼層 (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

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

ExtendedProtectionSelectorDelegate ExtendedProtectionSelectorDelegate ExtendedProtectionSelectorDelegate ExtendedProtectionSelectorDelegate

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

取得值,表示是否已啟動 HttpListenerGets 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 的淺層複本 (Shallow Copy)。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.

適用於

另請參閱