Search code examples
c#httpwebrequesthttp-status-code-401

Ignore 401 Unathorized in HttpWebRequest


A third-party website returns 401 instead of 200 in its regular workflow. Browsers ignore 401 and display the received HTML content, so users do not even aware there was 401. But HttpWebRequest throws HttpException. How can I ignore it and get response instead?


Solution

  • Your code throws WebException, so the solution to get the result is : put your entire code in try catch block, catch block must catch WebException, and write following code in your catch block to get the html content.

        try
        {
          // your code here
        }                
        catch (WebException e2)
        {
           using (WebResponse response = e2.Response)
            {
             HttpWebResponse httpResponse = (HttpWebResponse)response;
             Console.WriteLine(" Error : {0}", httpResponse.StatusCode);
             using (Stream data = response.GetResponseStream())
             using (var reader = new StreamReader(data))
             {  
    //the html content is here
                string text = reader.ReadToEnd();
                Console.WriteLine(text);
             }
            }
    }