ASP.NET HttpClient请求返回409错误

时间:2018-08-28 15:33:41

标签: c# http dotnet-httpclient http-status-code-409

我正在像这样进行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错误调用,但是如果我注释掉第一个请求。内容并取消注释第二个请求。它起作用了,我得到的响应码为200。

我认为这些都是导致409错误的原因:

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

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

1 个答案:

答案 0 :(得分: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文档。您走在正确的轨道上。