Coding⏱️ 2 min read📅 2026-05-31

How to Fix code 400 Error – .Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

Handle HttpWebRequest exceptions for HTTP status code 400 (Bad Request) to retrieve error messages.

Quick Answer: Use the ResponseStream property and read the response content as a string to handle the exception and extract the error message.

When working with HTTP requests in .NET, it's not uncommon to encounter status codes that indicate a problem with the request. One such code is 400, which indicates a bad request. However, when this code is returned by the server, .NET's HttpWebRequest class can throw an exception.

🛑 Root Causes of the Error

  • The root cause of this issue is that .NET's HttpWebRequest class only handles HTTP responses with a status code between 200 and 299. When a response has a status code outside this range, it throws an exception.

🚀 How to Resolve This Issue

Method 1: Parse the Response Content

  1. Step 1: Use the GetResponseStream method to get the response stream.

Method 2: Check the Status Code Before Calling GetResponse

  1. Step 1: Use the StatusCode property to check if the status code is between 200 and 299.

🎯 Final Words

By following these methods, you can handle HTTP responses with status codes outside the 200-299 range and avoid exceptions. Remember to always check the status code before calling GetResponse to ensure a smooth and reliable experience.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions