Keywords: .NET | HttpWebRequest | HTTP 400 | WebException | error handling
Abstract: This article explains how to handle HTTP 400 status codes when using .NET's HttpWebRequest, which raises exceptions on non-success codes. It covers accessing the response via WebException for effective error handling, with code examples and best practices.
Introduction
In .NET development, the HttpWebRequest class is commonly used for making HTTP requests. However, when the server returns an HTTP 400 (Bad Request) status code, the GetResponse() method throws a WebException. This behavior aligns with HTTP protocol handling of non-success codes but can be problematic in scenarios like RESTful APIs where 400 responses may contain valuable error details in the response body.
Behavior of HttpWebRequest
By default, HttpWebRequest.GetResponse() throws a WebException for HTTP status codes outside the 200 series (success codes). For instance, a 400 status indicates a client error, and the server might include structured error information in the response. This prevents direct access to the response content, requiring developers to retrieve it indirectly through exception handling.
Accessing Response via WebException
To address this, you can catch the WebException and access the HTTP response through its Response property. Even for non-success status codes, the Response may contain useful information. The following example demonstrates this approach.
Code Example
The code below illustrates how to catch a WebException and extract the status code and response content. We encapsulate the logic in a helper function for reusability.
using System;
using System.IO;
using System.Net;
public class HttpRequestHelper
{
public static void HandleRequest(string url)
{
WebRequest request = WebRequest.Create(url);
try
{
using (WebResponse response = request.GetResponse())
{
// Handle successful response
Console.WriteLine("Request succeeded");
}
}
catch (WebException e)
{
if (e.Response != null)
{
HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
Console.WriteLine($"Error code: {httpResponse.StatusCode}");
using (Stream stream = e.Response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string content = reader.ReadToEnd();
Console.WriteLine($"Response content: {content}");
}
}
else
{
// Handle cases with no response, such as network failures
throw;
}
}
}
}In this code, a try-catch block is used to capture the WebException. If the Response is not null, it is cast to HttpWebResponse to obtain the status code, and the response content is read via GetResponseStream(). This ensures access to error information even when the server returns a 400 status code.
Best Practices and Recommendations
For better code organization, it is advisable to encapsulate this logic into a separate method. Additionally, if error responses are expected to be large, adjust the HttpWebRequest.DefaultMaximumErrorResponseLength property to capture the full content. Always handle cases where Response is null, such as during timeouts or connection failures.
Conclusion
By catching WebException and accessing the Response property, developers can effectively handle HTTP 400 and other non-success status codes, extracting key information from the response. This approach not only resolves the issue of exception interruptions but also enables more flexible API error handling, enhancing application robustness.