使用c# HttpClient进行参数化查询

joh*_*yne 2 c# json httpclient visual-studio

我正在发送一个 httpclient 请求,如下所示。我想通过 get 请求发送一个参数。我怎样才能做到这一点 ?或者说怎样才能正确使用呢?

例如; 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 12

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

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}")
Run Code Online (Sandbox Code Playgroud)