带有Json正文的HttpClient Post请求

时间:2019-07-17 16:14:36

标签: c# api asp.net-core dotnet-httpclient

我正在尝试向URL中带有JSON正文和参数(POST)的API发送param请求。

请求进行得很好,但是从API发送回的响应表明customObj的值未传递到API?

我已经多次更改了实现,但是似乎无法弄清楚为什么正文消息无法通过?我检查了curl,可以看到它包含正文和JSON消息。

我唯一想到的是Content-Type:application/json-patch+json,而应该只有application/json

class customObj{
    public string param1 {get;set;}
    public string param2 {get;set;}
    public string param3 {get;set;}
}
string result;
var url = $"/test/{param}/dothis";

var jSonData = JsonConvert.SerializeObject(customObj);

using (var httpClient = new HttpClient())
{
    httpClient.BaseAddress = new Uri("https://www.testapi.com");

    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    using (var response =
        await httpClient.PostAsync(url, new StringContent(jSonData, Encoding.UTF8, "application/json")))
    {
        using (var content = response.Content)
        {
            var result = await content.ReadAsStringAsync();
        }
    }
}

CURL

curl -X POST "<url>" -H "accept: application/json" 
-H "Content-Type: application/json-patch+json" -d "{ \"param1\": \"test1\", \"param2\": \"test2\", \"param3\": \"test3\"}"

1 个答案:

答案 0 :(得分:0)

最终解决了这个问题。该问题是由于我在PascalCasing正文中使用了Json,而终点使用了camelCasing,因此无法读取属性值。

所以代替这个

var jSonData = JsonConvert.SerializeObject(customObj);

在对json对象进行序列化时,我不得不使用骆驼肠衣解析器。

var changePassObj = JsonConvert.SerializeObject(customObj, 
                new JsonSerializerSettings 
                { 
                    ContractResolver = new CamelCasePropertyNamesContractResolver() 
                });