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

myzjeezk  于 2023-05-02  发布在  C#
关注(0)|答案(2)|浏览(191)

我尝试以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格式发送请求?

fquxozlt

fquxozlt1#

试试这个

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

//or you can use an anonymous type
//var data = new 
//{
//  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);
   
  double value = result.Return;
  string name = Result.Name;
  }
gk7wooem

gk7wooem2#

我会先使用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;
}

只需要将字典作为body对象传入即可--不过我建议创建一个DTOS类来发送。
然后,您可以获得返回的RestResponse对象的某些方面,如:

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

相关问题