在C#中使用HttpClient与原始Json进行POST API

时间:2018-11-21 13:03:05

标签: c# api httpclient

我无法获得以下POST请求来工作。无论我尝试什么,它都会返回状态消息 400(错误请求)

static HttpClient client = new HttpClient();

   client.BaseAddress = new Uri("<<REDACTED>>"); 
   client.DefaultRequestHeaders.Accept.Clear();
   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

   // authorisation credentials go here, which work

  var model = JsonConvert.SerializeObject(dialApi); //, Encoding.UTF8, "application/json"); //.DeserializeObject<Hello>(result);
  var model1 = new StringContent(model, Encoding.UTF8, "application/json");
  var x = "{\"data\":{\"Dest\":\"<<REDACTED>>\"}}";

  //HttpResponseMessage response = await client.PostAsJsonAsync(path, model1);
  HttpResponseMessage response = await client.PostAsJsonAsync(path, new StringContent(x, Encoding.UTF8, "application/json"));

问题可能是'Content'->'Headers'->'ContentType'为'text / html'(应该为'application / json',但我似乎无法更改。默认标题已经设置为“ application / json”

enter image description here

我应该补充一点,我的API是在Postman中工作的,主体的原始设置为“ application / json”:

enter image description here

我想知道是否有人可以提供帮助?

更新:

我已经尝试了“重复”问题的答案中给出的替代实现,但它也无法正常工作:

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, path);
        request.Content = new StringContent("{\"data\":{\"Dest\":\"<<>>redacted\"}}",
                                Encoding.UTF8,
                                "application/json");//CONTENT-TYPE header

        await client.SendAsync(request)
                  .ContinueWith(responseTask =>
                  {
                      Console.WriteLine("Response: {0}", responseTask.Result);
                  });

在控制台上打印以下内容:

enter image description here

0 个答案:

没有答案