You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用HttpClient获取409状态码的HTTP POST响应体并反序列化

Alright, let's figure out why you can't access that 409 response body and fix it step by step.

What's Missing in Your Current Code?

Right now, your code only retrieves the HttpResponseMessage object, but you never actually read the content stream that contains the error JSON. Also, using .Result on the async PostAsync call is a bad practice—it can cause deadlocks in certain contexts (like ASP.NET) and defeats the purpose of async operations. We'll fix both issues.

Step 1: Create a Strongly-Typed Model for the Error Response

To deserialize the JSON response into something usable, make a simple class that matches the structure of the error body:

// If using System.Text.Json (.NET Core/.NET 5+)
using System.Text.Json.Serialization;

public class ApiErrorResponse
{
    [JsonPropertyName("message")]
    public string Message { get; set; }

    [JsonPropertyName("errorDescription")]
    public string ErrorDescription { get; set; }
}

// OR if using Newtonsoft.Json (Json.NET)
// using Newtonsoft.Json;
// public class ApiErrorResponse
// {
//     [JsonProperty("message")]
//     public string Message { get; set; }
//
//     [JsonProperty("errorDescription")]
//     public string ErrorDescription { get; set; }
// }

Step 2: Rewrite Your HttpClient Code to Read and Deserialize the Response

We'll switch to async/await (the recommended way to use HttpClient) and explicitly read the response content, even for error status codes like 409:

using System.Net.Http;
using System.Text;
using System.Text.Json; // Or Newtonsoft.Json if you prefer
using System.Threading.Tasks;

public async Task UpdateInspectionAsync()
{
    // Pro tip: HttpClient should be reused as a singleton (don't create a new one every time)
    using var client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:60129");

    var model = new Inspection 
    { 
        CategoryId = 1, 
        InspectionId = 0, 
        Descriptor1 = "test descriptor 121212", 
        Name = "my inspection 1121212" 
    };

    // Replace the outdated JavaScriptSerializer with modern JSON libraries
    string json = JsonSerializer.Serialize(model);
    // Or with Newtonsoft: string json = JsonConvert.SerializeObject(model);

    var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
    HttpResponseMessage response = await client.PostAsync("api/Inspections/UpdateInspection", stringContent);

    // Read the response body FIRST—regardless of success or failure
    string responseBody = await response.Content.ReadAsStringAsync();

    if (!response.IsSuccessStatusCode)
    {
        // Handle error responses
        if (response.StatusCode == System.Net.HttpStatusCode.Conflict) // 409
        {
            // Deserialize the error JSON into our model
            ApiErrorResponse errorResponse = JsonSerializer.Deserialize<ApiErrorResponse>(responseBody);
            // Now you can access the error details!
            // Example: Console.WriteLine($"Error: {errorResponse.Message} - {errorResponse.ErrorDescription}");
        }
        // Add handling for other error status codes if needed
    }
    else
    {
        // Handle successful response here
    }
}

Key Things to Remember

  • Avoid .Result for async calls: Always use await to prevent deadlocks and maintain proper async flow.
  • Retire JavaScriptSerializer: It's obsolete—use System.Text.Json (built into .NET Core+) or Newtonsoft.Json for better performance and features.
  • Read response content for errors: Error status codes (like 409) still have a response body, but you have to explicitly read it with ReadAsStringAsync().

内容的提问来源于stack exchange,提问作者ScottG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:21:26