Code With Wolf


Making API Requests with .NET / C#

Making API Requests with .NET / C

If you are following my blog, most likely you are a JavaScript developer. I promise that I am right there with you. I love the open source nature of the JS community!

I currently signed a contract with a small company that has me working on the server-side using .NET, so this week I have been stepping up my C# skills and working on ASP.NET Core 1.1, which is a very exciting new opensource, fast, cross platform framework by Microsoft.

If you are a JavaScript developer, stick with me here because I think you’ll be surprised what making HTTP requests are like with .NET and it is a cool comparison with your favorite AJAX library.

HttpClient

So HttpClient is your HTTP request library, think jQuery or axios.

Let’s set up an easy .NET Console Application to build an internet browser in our console. This is a simple project, so if you have .NET installed on your machine and you’ve built the .NET “Hello World” console app, feel free to follow along.

Create a console app.

>>> cd <PATH>
>>> mkdir HttpClientTutorial
>>> cd HttpClientTutorial

The next step is new to .NET version 4.6.

If you are a .NET developer then you have already skipped this because you are using Visual Studio. If you have been using Yeoman for small console applications, you can do that or the new way in version 4.6 is that you specify what kind of app you are building (console, api, and mvc are some of your options).

Once you type dotnet new into your console, .NET will prompt you through this if it is your first time. I recommend upgrading to the most recent .NET version here, if you haven’t yet.

>>> dotnet new console
>>> dotnet restore

We just created a blank console app. We should have our Main() method in the Program class now.

  1. Use System.Net.Http
Using System;
/***Make sure to use .Net.Http, otherwise they will throw an error and remind you. ***/
Using System.Net.Http; 
//Below is the default console app that .NET set up for us from our command line. 
namespace HttpClientTutorial
{
   class Program
 { 
   static void Main(string[] args)
  {
     Console.WriteLine("Hello World");
  }
 }
}
  1. Create a Method for the GET request. We will call it GetData()
/* Add the following static method to your Program class, after the 
* Main() method.
*
* It's good practice to keep these requests asynchronous. .NET uses * async/await just like ES2017. */ 

static async void GetData()
    {
        //We will make a GET request to a really cool website...
       
         string baseUrl = "http://mwolfhoffman.com";
        //The 'using' will help to prevent memory leaks.
        //Create a new instance of HttpClient
        using (HttpClient client = new HttpClient())
        
        //Setting up the response...         
        
  using (HttpResponseMessage res = await client.GetAsync(baseUrl))
        using (HttpContent content = res.Content)
        {
            string data = await content.ReadAsStringAsync();
            if (data != null)
        {
            Console.WriteLine(data);
        }
    }
}
  1. Add the method to the Main() function so we will invoke it when we run our app.
static void Main(string[] args)
   {
    GetData();
    Console.ReadLine();
    Console.ReadKey();
   }
  1. Run the app

    >>> dotnet run

We just did a GET request to my website, and we are receiving the HTML in our console. Pretty cool. We just created a web browser.

That’s how you do a GET request with .NET. I have been using the new .NET Core 1.1 and it works, but I have been told there might be a few differences depending on what version you are using.

As far as my research goes, that is the easiest way to make requests with .NET.

As usual, the documentation is pretty good and you can read more about the various methods here.

For instance, to do a PUT request, you would use the PutAsync(uri, HttpContent) method instead of the GetAsync(uri).

For the JavaScript devs that followed along, you can see it’s a little more writing than our typical AJAX request. We love working with our promises and callbacks, but even JavaScript is starting to use async/await, which is a pretty cool feature.

I hope you learned something, as always feel free to comment with questions, concerns, or something else that you learned about HttpClient.

</>



© 2022 Code With Wolf