Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass request content with HttpClient GetAsync method in c#

Tags:

c#

How do I pass request content in the HttpClient.GetAsync method? I need to fetch data depending upon request content.

[HttpGet]
public async Task<HttpResponseMessage> QuickSearch()
{
    try
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Clear();
            HttpResponseMessage response =await client.GetAsync("http://localhost:8080/document/quicksearch");

            if (response.IsSuccessStatusCode)
            {
                Console.Write("Success");
            }
like image 454
Arya Raj Avatar asked Jul 12 '26 04:07

Arya Raj


2 Answers

If you are using .NET Core, the standard HttpClient can do this out-of-the-box. For example, to send a GET request with a JSON body:

HttpClient client = ...

...

var request = new HttpRequestMessage
{
    Method = HttpMethod.Get,
    RequestUri = new Uri("some url"),
    Content = new StringContent("some json", Encoding.UTF8, ContentType.Json),
};

var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();

var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
like image 191
Sonali Jain Avatar answered Jul 15 '26 02:07

Sonali Jain


If you want to send content, then you need to send it as query string (According to your API route)

HttpResponseMessage response =await client.GetAsync("http://localhost:8080/document/quicksearch/paramname=<dynamicName>&paramValue=<dynamicValue>");

And in API check for "paramName" and "paramValue"

like image 22
Colonel Software Avatar answered Jul 15 '26 02:07

Colonel Software