Search code examples
c#.netwebrequest

WebRequest.GetResponse(): read response, even on a 401?


I'm having trouble with the authorization piece of a third-party API. The API is shooting me a 401 in the HTTP Status Code, and more info in the response body.

   var req = HttpWebRequest.Create(url);
   req.Method = "GET";

   var resp = req.GetResponse();

This is the code I typically use, but GetResponse() throws an exception on the 401 and I never get the response body.

Is there another implementation of this request I'm missing, or another way to do this in .NET so that I can get the response even when the request generates a 401?

Thanks.


Solution

  • web exception

    The WebException contains a Response object that you can use to read the response body