Search code examples
c#.netconsole-applicationhttpclientwebrequest

'WebRequest.Create(string)' is obsolete: 'WebRequest, Use HttpClient instead.'


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();

Solution

  • 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?