代码之家  ›  专栏  ›  技术社区  ›  Ege Bayrak

使用HttpClient发送自定义数据类型列表

  •  0
  • Ege Bayrak  · 技术社区  · 6 年前

    我试图将自定义数据类型的列表发送到API控制器内的函数,但无法使其正常工作。

    这是我定制的数据类型

    public class MinimalStatementModel
    {
    public int ActivityID { get; set; }
    public string StatementCode { get; set; }
    public string Value { get; set; }
    public string Note { get; set; }
    }
    

    这是 HttpClient 部分

    static async Task UpdateActivityStatement()
            {
                string uri = "/api/ExtraNet/UpdateActivityStatement";
    
                HttpClient client = new HttpClient();
    
                int ActivityId = 12345; //Aktivite Numarası
                string StatementCode = "123456";
                string Value = "Test";
                string Note = "Test";
    
                string token = ""
    
                client.BaseAddress = "address"
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                client.Timeout = TimeSpan.FromMinutes(30);
    
    
                var postData = "{ \"ActivityID\":\"" + ActivityId + "\"" + ","
                                 +"\"StatementCode\":\"" + StatementCode + "\"" + ","
                                 +"\"Value\":\"" + Value + "\"" +"," 
                                 +"\"Note\":\"" + Note + "\"}";
    
                var content = new StringContent(postData, Encoding.UTF8, "application/json");
    
                HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, uri);
                message.Headers.Add("Authorization", string.Format("bearer {0}", token));
                message.Content = content;
    
                HttpResponseMessage response = await client.SendAsync(message);
    
                var responseJson = await response.Content.ReadAsStringAsync();
    
                Console.WriteLine(responseJson);
            }
    

    这是API控制器的一部分

    public ResponseHelper UpdateActivityStatement(List<MinimalStatementModel> requestList)
            {
                //releveant codes
            }
    

    我可以使用自定义数据类型和HttpClient,但是自定义数据类型的列表花费的时间比我想象的要长。

    我怎样才能做到这一点?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Nkosi    6 年前

    JSON是单个对象,而不是列表/数组。将对象括在方括号中(“ [] )表示集合。

    var postData = "[{ \"ActivityID\":" + ActivityId.ToString() + ","
                 +"\"StatementCode\":\"" + StatementCode + "\"" + ","
                 +"\"Value\":\"" + Value + "\"" +"," 
                 +"\"Note\":\"" + Note + "\"}]";
    
        2
  •  0
  •   Mohammad    6 年前

    更好的解决方案可能是:

        var json = JsonConvert.SerializeObject( new 
        {
         str.StatementCode = "123456",
         str.Value = "Test",
         str.Note = "Test"
        });
       //construct content to send
        var content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
    
    推荐文章