0

我正在像这样进行 HTTP 调用:

[HttpGet]
public HttpResponseMessage updateRegistrant(string token, string registrantId, string firstname, string lastname, string postalCode, string phoneNumber, string city, string email)
{
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.BaseAddress = new Uri("https://api.example.com/v1/registrants/" + registrantId + "/");
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, "person/contact-information");

        request.Content = new StringContent("{\"firstName\":\"" + firstname + "\", \"lastName\":\"" + lastname + "\", \"phones\":[{\"phone\":\"" + phoneNumber + "\", \"type\":\"Home\", \"primary\":true}], \"emails\":[{\"email\":\"" + email + "\", \"type\":\"Personal\", \"primary\":true}], \"addresses\":[{\"city\":\"" + city + "\", \"zipCode\":\"" + postalCode + "\"}]}", Encoding.UTF8, "application/json");

        //request.Content = new StringContent("{\"firstName\":\"" + firstname + "\", \"lastName\":\"" + lastname + "\"}", Encoding.UTF8, "application/json");

        HttpResponseMessage response = httpClient.SendAsync(request).Result;

        return response;
    }
}

现在,当我运行此方法时,我得到 409 错误调用,但是如果我注释掉第一个 request.Content 并取消注释第二个 request.Content 它可以工作,我得到的响应代码为 200。

我会假设这些导致 409 错误:

\"phones\":[{\"phone\":\"" + phoneNumber + "\", \"type\":\"Home\", \"primary\":true}]

但是为什么以及如何解决这个问题?

4

1 回答 1

1

与其尝试手动构建 JSON 字符串,不如考虑这样的方法。

string firstname = "";
string lastName = "";
string phoneNumber = "";
string primary = "";
string phoneNumber2 = "";

var registrant = new
{
    firstName = firstname,
    lastName = lastName,
    phones = new[]
    {
        new { phone = phoneNumber, type = "Home", primary = true },
        new { phone = phoneNumber2, type = "Work", primary = false }
    }
};

JavaScriptSerializer js = new JavaScriptSerializer();
string jsonData = js.Serialize(registrant);

以您可以更轻松地自行排除故障的方式构建您的请求,可以帮助您回答自己的问题并具体找出导致错误的数据部分。它还将帮助您在构建 JSON 时避免任何基本的拼写错误。

409 可以是任何东西。检查响应对象以获取可能包含更多信息的人类可读错误消息。通常,这意味着您更新的数据与某些内容发生冲突。电话、地址等。从一个已知的工作请求开始,一次添加一个元素。

如果您可以具体缩小导致服务器返回 409 的数据的范围,那么请返回并更仔细地查看他们的 API 文档。你在正确的轨道上。

于 2018-08-28T16:20:21.480 回答