HttpListener.EndGetContext(IAsyncResult) Method

Definition

Completes an asynchronous operation to retrieve an incoming client request.

C#
public System.Net.HttpListenerContext EndGetContext(IAsyncResult asyncResult);

Parameters

asyncResult
IAsyncResult

An IAsyncResult object that was obtained when the asynchronous operation was started.

Returns

An HttpListenerContext object that represents the client request.

Exceptions

asyncResult was not obtained by calling the BeginGetContext(AsyncCallback, Object) method.

asyncResult is null.

A Win32 function call failed. Check the exception's ErrorCode property to determine the cause of the exception.

The EndGetContext(IAsyncResult) method was already called for the specified asyncResult object.

This object is closed.

Examples

The following code example shows the implementation of a callback method that calls the EndGetContext method.

C#
public static void ListenerCallback(IAsyncResult result)
{
    HttpListener listener = (HttpListener) result.AsyncState;
    // Call EndGetContext to complete the asynchronous operation.
    HttpListenerContext context = listener.EndGetContext(result);
    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();
}

Remarks

The EndGetContext method is called, usually within an application-defined callback method invoked by a delegate, to obtain the HttpListenerContext object that contains an incoming client request and its associated response. This method completes an operation previously started by calling the BeginGetContext method. If the operation has not completed, this method blocks until it does.

Because calling the EndGetContext method requires the HttpListener object, this object is typically passed into a callback method by using the state object passed into the BeginGetContext method. You can obtain this state object by using the AsyncState property of the asyncResult object.

For detailed information about using the asynchronous programming model, see Calling Synchronous Methods Asynchronously.

Notes to Callers

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in the .NET Framework.

Applies to

Product Versions
.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