Search code examples
c#dotnet-httpclient

How can I translate Webrequest method in HttpClient


I have this code for recovering Http code and description, but Visual Studio says that WebRequest is obsolete and that I have to use HttpClient. I'm not familiar with HttpClient can you help me?

IConfigurationRoot config;

myRequest = WebRequest.CreateHttp($"{config["BASE_URL"]}{link}");
myResponse = (HttpWebResponse)myRequest.GetResponse();
Check_load($"{config["BASE_URL"]}{link}");

var code = ((int)myResponse.StatusCode);  
var desc = myResponse.StatusDescription;

Solution

  • var client = new HttpClient();
    var response = await client.GetAsync(url);
    var statusCode = response.StatusCode;
    var content = response.Content;
    if(statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created){
       //return something, error, description
    }
    
    

    Update
    From comment @Charlieface pointed out where I haven't declared HttpClient as static field.
    To avoid creating instances of HttpClient every time it is called, the complete workground as below.

    public class HttpHelper{
       private static HttpClent client = new HttpClient();
    
       public static async Task<string> GetAsync(string url)
       {
          var response = await client.GetAsync(url);
          var statusCode = response.StatusCode;
          var content = response.Content;
          if(statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
          {
             //return something, error, description
             //return $"error with status code: {statusCode}";
          }
          else
          {
             //return "success";
          }
       }
    }