【问题标题】:c # send parameters when sending json get requestc#发送json get请求时发送参数
【发布时间】:2021-05-23 22:12:23
【问题描述】:

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

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

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



    }
}

【问题讨论】:

    标签: c# json rest json.net


    【解决方案1】:

    发送带有 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 规范的灰色区域!

    【讨论】:

    • 嗯,有没有办法用参数做到这一点?所以通过重写查询代码
    【解决方案2】:

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

    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
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      • 1970-01-01
      相关资源
      最近更新 更多