HttpListener.GetContext 方法

定義

等候傳入要求,並在收到要求時傳回。

C#
public System.Net.HttpListenerContext GetContext();

傳回

HttpListenerContext 物件,代表用戶端要求。

例外狀況

Win32 函式呼叫失敗。 請檢查例外狀況的 ErrorCode 屬性,以判斷造成例外狀況的原因。

這個物件尚未啟動或目前已停止。

-或-

HttpListener 沒有任何要回應的統一資源識別元 (URI) 前置詞。

這個物件已經關閉。

範例

下列程式代碼範例示範如何呼叫這個方法。

C#
// 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();
}

備註

在呼叫這個方法之前,您必須呼叫 Start 方法,並新增至少一個 URI 前置詞來接聽,方法是將 URI 字串新增至 HttpListenerPrefixCollection 屬性所傳回的 Prefixes 。 如需前置詞的詳細描述,請參閱 HttpListener 類別概觀。

此方法會在等候傳入要求時封鎖。 如果您想要在個別線程) 以異步方式處理傳入要求 (,讓應用程式不會封鎖,請使用 BeginGetContext 方法。

給呼叫者的注意事項

在應用程式中啟用網路追蹤時,這個成員會輸出追蹤資訊。 如需詳細資訊,請參閱 .NET Framework 中的網路追蹤

適用於

產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1