c # 发送json get请求时发送参数

时间:2021-02-21 13:11:51

标签: c# json rest json.net

我正在开发一个应用程序,使 api 在 c# windowsforms 上获取、发布、删除、更新请求。

我的问题是:我想在请求获取时在“正文”中发送一个参数。我该怎么做?

using System.Net.Http;
using System;
using System.Threading.Tasks;
using HastaTakip.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Text;


namespace HastaTakip.Api
{
    public class CustomersRepository
    {
        public HttpClient _client;
        public HttpResponseMessage _response;
        public HttpRequestMessage _requestMessage;
    
        public CustomersRepository()
        {
            _client = new HttpClient();
            _client.BaseAddress = new Uri("http://localhost:3000/");
            _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImZ0aG1seW16QGhvdG1haWwuY29tIiwidXNlcklkIjoxLCJpYXQiOjE2MTM5MDY5NDMsImV4cCI6MTYxNDA3OTc0M30.NER1RMTYx41OsF26pjiMXY-pLZTE-pIg4Q73ehwGIhA");
            _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        }



        public async Task<CustomersModel> GetList()
        {
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("business_code", "dental")
            });

            _response = await _client.GetAsync(content);
            var json = await _response.Content.ReadAsStringAsync();
            var listCS = CustomersModel.FromJson(json);
            return listCS;
        }



    }
}

2 个答案:

答案 0 :(得分:0)

发送带有 JSON 正文的 GET 请求:

    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);

但是带有正文的 HTTP GET 是一种有点非常规的构造,属于 HTTP 规范的灰色区域!

答案 1 :(得分:0)

你最好为你的内容数据创建一个类:

public class RequestData
{
  pubic string BusinessCode {get; set;}
{

在此之后您可以创建您的内容对象

public async Task<CustomersModel> GetList()
{
   var data=new RequestData{BusinessCode="dental"}
   var stringData = JsonConvert.SerializeObject(data);
   contentData = new StringContent(stringData, Encoding.UTF8, "application/json");

var response = await _client.GetAsync(contentData);

// but I am not sure that Get will work correctly so I recommend to use

   var response = await _client.PostAsync(contentData);


   if (response.IsSuccessStatusCode)
   {
   var stringData = await response.Content.ReadAsStringAsync();
   return JsonConvert.DeserializeObject<CustomersModel>(stringData);
   }
   else
   {
     ....error code
   }
}