在 http post 请求中发送 JSON 数据 C#

Send JSON data in http post request C#

我正在尝试发送 JSON 格式的 http post 请求,格式应如下所示:

{ 
"id":"72832",
"name":"John"
}

我试过像下面那样做,但如果我是正确的,这不是发送 json 格式的请求。

var values = new Dictionary<string,string>
{
    {"id","72832"},
    {"name","John"}
};

using (HttpClient client = new HttpClient())
{
    var content = new FormUrlEncodedContent(values);
    HttpResponseMessage response = await client.PostAsync("https://myurl",content);
    // code to do something with response
}

如何修改代码以 json 格式发送请求?

试试这个

using (var client = new HttpClient())
{
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
var baseAddress = "https://....";
var api = "/controller/action";
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Add(contentType);

var data = new Dictionary<string,string>
{
    {"id","72832"},
    {"name","John"}
};

var jsonData = JsonConvert.SerializeObject(data);
var contentData = new StringContent(jsonData, Encoding.UTF8, "application/json");

var response = await client.PostAsync(api, contentData);

  if (response.IsSuccessStatusCode)
  {
  var stringData = await response.Content.ReadAsStringAsync();
  var result = JsonConvert.DeserializeObject<object>(stringData);
  }
}

更新

如果请求以 `

的形式返回 Json 数据
 { "return":"8.00", "name":"John" }

您必须创建结果模型

public class ResultModel
{
  public string Name {get; set;}
  public double Return {get; set;}
}

代码将是

if (response.IsSuccessStatusCode)
  {
  var stringData = await response.Content.ReadAsStringAsync();
  var result = JsonConvert.DeserializeObject<ResultModel>(stringData);
   
  var value=result.Return;
  var name=Result.Name;

  }

我会先使用 RestSharp。

dotnet add package RestSharp

然后你可以这样发送请求:

public async Task<IRestResult> PostAsync(string url, object body)
{
    var client = new RestClient(url);
    client.Timeout = -1;

    var request = new RestRequest(Method.Post);
    request.AddJsonBody(body);

    var response = await client.ExecuteAsync(request);
    return response;
}

只需将您的字典作为正文对象传入 - 我建议创建一个 DTOS class 来发送。

然后您可以获得返回的 RestResponse 对象的某些方面,例如:

var returnContent = response.Content;
var statusCode = response.StatusCode;