json C#无法使用HttpRequestMessage发布数据并获得400状态

velaa5lx  于 2023-04-08  发布在  C#
关注(0)|答案(3)|浏览(191)

我尝试了几种不同的方法,都无法获取pipelineId来post(receive 400),代码如下:

{
                client.BaseAddress = new Uri(_serviceConfig.DataGapsBaseUrl);
                var request = new HttpRequestMessage(HttpMethod.Post, "/piper/jobs");

                var jsonContent = new StringContent(JsonConvert.SerializeObject(new
                {
                    pipelineId = _serviceConfig.DataPipelineId
                }), Encoding.UTF8, "application/json");
                
                request.Content = jsonContent;

                var token = await GetToken();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.ToString());

                var result = await client.SendAsync(request);

                var json = JsonConvert.DeserializeObject<JToken>(result.Content.ReadAsStringAsync().Result);
                var jobId = json["id"].ToString();
                return jobId;
            }
        }

当我使用Postman与上面相同的操作时,我得到200个状态和结果:

qyyhg6bp

qyyhg6bp1#

因为你使用的是async await,所以在任何地方都使用它,而且这种语法更常见

using HttpClient client = new HttpClient { BaseAddress = new Uri(baseUri) };

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.ToString());

var jsonContent = new StringContent(JsonConvert.SerializeObject(new
                {
                    pipelineId = _serviceConfig.DataPipelineId
                }), Encoding.UTF8, "application/json");

 var response = await client.PostAsync(uri, jsonContent);

 var json = await response.Content.ReadAsStringAsync();

var jObj = JObject.Parse(json);
var createTime =  (string) jObj["createTime"]; //I can't see Id in Postman
yyyllmsg

yyyllmsg2#

对于初学者:

  • 您忘记序列化StringContent
var jsonContent = new StringContent(JsonConvert.SerializeObject(new
                {
                    pipelineId = _serviceConfig.DataPipelineId
                }), Encoding.UTF8, "application/json");

也使用await更改以下内容以防止线程锁定

var json = JsonConvert.DeserializeObject<JToken>(await result.Content.ReadAsStringAsync());

请注意,如果您的客户端是单例,并且您正在从异步上下文设置身份验证,则它可能会被另一个调用覆盖,要么重新创建客户端,要么在HttpRequestMessage上设置授权:

var request = new HttpRequestMessage(HttpMethod.Post, "/piper/jobs");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.ToString()
6tqwzwtp

6tqwzwtp3#

对不起,朋友们,我的错,我需要发送这个:
{“pipelineId”:“zxxzxzxzxz18”,“input”:{“Batch_Id”:9999}}
需要弄清楚如何处理双引号,它修复了这个问题。

相关问题