make a http request with url parameters in csharp

To make an HTTP request with URL parameters in C#, you can use the HttpClient class from the System.Net.Http namespace. Here's an example:

main.cs
using System.Net.Http;
using System.Threading.Tasks;

public async Task<string> MakeRequestAsync()
{
    // Create an instance of HttpClient
    HttpClient httpClient = new HttpClient();

    // Build the URL with parameters
    string url = "http://example.com/api/resource";
    var parameters = new Dictionary<string, string>
    {
        { "param1", "value1" },
        { "param2", "value2" }
    };
    url += "?" + string.Join("&", parameters.Select(kv => $"{kv.Key}={kv.Value}"));

    // Make the request
    HttpResponseMessage response = await httpClient.GetAsync(url);

    // Read the response content as a string
    string responseBody = await response.Content.ReadAsStringAsync();

    return responseBody;
}
725 chars
26 lines

In this example, we create an instance of HttpClient and build the URL with parameters by appending them to the base URL. We then use the GetAsync method of HttpClient to make the request and retrieve a HttpResponseMessage object. Finally, we read the response content as a string using the ReadAsStringAsync method of the response's Content property.

gistlibby LogSnag