Search code examples
c#jsonvisual-studiohttpclient

Parameterized query with c # HttpClient


I am sending an httpclient request as below. I want to send a parameter with a get request. How can I do that ? Or how can I use it properly?

For example; http://localhost:3000/users?business_code=123

using System.Net.Http;
using System;
using System.Threading.Tasks;
using MyApplication.Models;

namespace MyApplication.Api
{
    public class ModelsRepository
    {
        public HttpClient _client;
        public HttpResponseMessage _response;
        public HttpRequestMessage _request;
    
        public ModelsRepository()
        {
            _client = new HttpClient();
            _client.BaseAddress = new Uri("http://localhost:3000/");
            _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImZ0aG1seW16QGhvdG1haWwuY29tIiwidXNlcklkIjoxLCJpYXQiOjE2MTM5NzI1NjcsImV4cCI6MTYxNDE0NTM2N30.-EVUg2ZmyInOLBx3YGzLcWILeYzNV-svm8xJiN8AIQI");
            _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        }



        public async Task<UsersModel> GetList()
        {
              _response = await _client.GetAsync($"users");
              var json = await _response.Content.ReadAsStringAsync();
              var listCS = UsersModel.FromJson(json);
              return listCS;
        }
    }
}

Solution

  • What exactly do you mean by "you have to send the variable as a parameter"? Does it mean you want to add parameters dynamically by number and name? In this case you could have e.g. a Dictionary as input and convert it into a query string:

    var queryParameters = new Dictionary<string, string>
    {
        { "business_code", "123" },
        { "someOtherParam", "456"}
    };
    var dictFormUrlEncoded = new FormUrlEncodedContent(queryParameters);
    var queryString = await dictFormUrlEncoded.ReadAsStringAsync();
    
    var response = await _client.GetAsync($"users?{queryString}")