HttpClient.GetAsync Method
Sends an HTTP GET request to the specified Uri and returns the response.
Parameters
requestUri: The address to send the GET request to.cancellationToken: A token that may be used to cancel the operation.completionOption: An enumeration value that indicates when a response is considered to be completed.
Returns
- A task object representing the asynchronous operation. The result of the task is a
HttpResponseMessagecontaining the response.
Remarks
This method sends a GET request to the specified requestUri. It is an asynchronous method that returns a Task<HttpResponseMessage>. The HttpResponseMessage object contains the server's response to the request.
The CancellationToken can be used to cancel the request if it takes too long or is no longer needed.
The HttpCompletionOption parameter allows you to specify when the asynchronous operation should be considered complete. By default, it's HttpCompletionOption.ResponseContentRead, meaning the entire response content has been read. You can set it to HttpCompletionOption.ResponseHeadersRead to complete the operation as soon as the headers are received, which can be useful for streaming large responses.
Important
It is recommended to use the same instance of HttpClient for all requests within an application. Creating a new HttpClient instance for each request can lead to socket exhaustion and performance degradation.
Example
The following code example demonstrates how to use HttpClient.GetAsync to retrieve content from a web page:
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
private static readonly HttpClient client = new HttpClient();
public static async Task Main(string[] args)
{
try
{
string url = "https://dotnet.microsoft.com/en-us/";
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode(); // Throws an exception if the status code is not a success code (2xx)
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody.Substring(0, 200) + "..."); // Display first 200 chars
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
}