用c#HttpClient参数化查询

Parameterized query with c # HttpClient

我正在发送一个 httpclient 请求,如下所示。我想发送带有获取请求的参数。我怎样才能做到这一点 ?或者如何正确使用它?

例如; 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;
        }
    }
}

“您必须将变量作为参数发送”到底是什么意思?这是否意味着你想通过数字和名称动态添加参数? 在这种情况下你可以有例如字典作为输入并将其转换为查询字符串:

var queryParameters = new Dictionary<string, string>
{
    { "business_code", "123" },
    { "someOtherParam", "456"}
};
var dictFormUrlEncoded = new FormUrlEncodedContent(dict);
var queryString = await dictFormUrlEncoded.ReadAsStringAsync();

var response = await _client.GetAsync($"users?{queryString}")