Send JSON via POST in C# and Receive the JSON returned?

前端 未结 4 904
耶瑟儿~
耶瑟儿~ 2020-12-02 09:59

This is my first time ever using JSON as well as System.Net and the WebRequest in any of my applications. My application is supposed to send a JSON

4条回答
  •  囚心锁ツ
    2020-12-02 10:48

    Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:

    // ...
    
    string payload = JsonConvert.SerializeObject(new
    {
        agent = new
        {
            name    = "Agent Name",
            version = 1,
        },
    
        username = "username",
        password = "password",
        token    = "xxxxx",
    });
    
    var client = new HttpClient();
    var content = new StringContent(payload, Encoding.UTF8, "application/json");
    
    HttpResponseMessage response = await client.PostAsync(uri, content);
    
    // ...
    

提交回复
热议问题