4

I upgraded my .NET application from the version NET5 to NET6 and placed with a warning that the WebRequest class was obsolete. I've looked at a few examples online, but using HttpClient doesn't automatically grab credentials like WebRequest does, as you need to insert them into a string manually.

How would I convert this using the HttpClient class or similar?

 string url = "website.com";
        WebRequest wr = WebRequest.Create(url);
        wr.Credentials = CredentialCache.DefaultCredentials;
        HttpWebResponse hwr = (HttpWebResponse)wr.GetResponse();
        StreamReader sr = new(hwr.GetResponseStream());
        
    
        sr.Close();
        hwr.Close();
Justin
  • 127
  • 1
  • 2
  • 15

1 Answers1

6

Have you tried the following?

var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
var response = await myClient.GetAsync("website.com");
var streamResponse = await response.Content.ReadAsStreamAsync();

more info around credentials: How to get HttpClient to pass credentials along with the request?

NavidM
  • 1,515
  • 1
  • 16
  • 27
  • 2
    And then read [You're using HttpClient wrong and it is destabilizing your software](https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/) followed by [You're (probably still) using HttpClient wrong and it is destabilizing your software](https://josef.codes/you-are-probably-still-using-httpclient-wrong-and-it-is-destabilizing-your-software/) – Caius Jard Mar 21 '22 at 09:52