How to make requests via C #? WebRequest vs HttpClient

0

I have a project in .Net Framework 4.6.1, and in my research I concluded that I can use the WebRequest to make requests to other web services via the backend.

  • I would like to be able to make requests using any HTTP verb .
  • You can also use the SSL / TLS protocol when needed.
  • Is the WebRequest class the only one available for this purpose?
  • In addition to the above requirements, considering performance and security, is this the best way to establish connections through the .NET platform?
  • Issue:

    Consider the following code snippets:

    Case 1:

    public class MyServiceController : ApiController
    {
        public void Post()
        {
            // ...
            using (var httpClient = new HttpClient())
            {
                var result = httpClient.GetAsync("https://pt.stackoverflow.com");
            }
            // ...
        }
    }
    

    Case 2:

    public class MyServiceController : ApiController
    {
        public void Post()
        {
            // ...
    
            var request = WebRequest.Create("https://pt.stackoverflow.com");
            request.Method = "GET";
            // ...
    
            using (var response = request.GetResponse())
            {
                // ...
            }
        }
    }
    
      

    1. If both can help me make a request in C #, what would be the   difference between them? What are the best scenarios?

         

    2. Both have support for any HTTP verb?

         

    3. Both have support for using the SSL / TLS protocol?

         

    4. Which is more performative?

         

    5.

    Some of them are obsolete and can give me security risks in the request?

        
    asked by anonymous 17.12.2018 / 13:12

    1 answer

    0

    HttpClient is the most current class to use (from 4.5), including ASP.NET Core (which I use), you can apply resiliency behaviors to micro-services by using Polly

  • This class allows the use of calls to multiple servers and hosts in the same instance and the amount you want.
  • You can derive it for your own specialized classes.
  • It was written using the TAP ( Task -based Asynchronous Pattern to handle asynchronous requests, use Await, manage pending requests etc ...
  • Abstracted a lot, being much easier to implement and with fewer lines of code.
  • Supports ssl
  • Macoratti has made a comparison you can find by clicking here

    I hope I have helped!

        
    02.01.2019 / 02:40