How to create a GET request from C# client

By | September 11, 2017

Hello, In this article I will show how we can make a web api GET request from C# code. This can be used as a quick reference if you are making a web api calls from your code. This is a step by step guide.

Become an Expert in Programming and Web Development.View all courses!

First let see the API which I will be calling. If you want to know how to create API with GET request, you can refer this article.

Below is the code of my web api class

As you can see in the above code I have to api calls(methods). One with parameter and one without parameter. And I will run the application on my local system.

I can access the above API by using the URL “localhost:59171/api/home/Get” or “localhost:59171/api/home/GetAllPerson”. The url can be different on your machine.

Now create a console application to access the api though HTTPClient in C#.

The HTTPCleint class is present under the System.Net.Http namespace. You need to add reference of the same namespace in your client.

In case if you are not able to find the above namespace you need to explicitly add the reference to the project and add the namespace as shown in the below code.

Get Request from C#

Now we can use the below code to call the first method i.e. Get which just returns a single name.

We will get the one name printed on the console. But suppose if you want to get all the persons present in the list. And we want to recreate the list at the client side. We can use Newtonsoft json convertor as shown in the code below.

The below code shows how we can convert a json string to .NET type  using json convertor

The person type should be known to the client.

Now  in the service there is a method which takes a string as parameter. If we want to call that para metered method of the web api we should use the below code.

As we can see in the web api code, there are very good chances that the person is not present in the list. In that case we are simply returning a string in the response.

And in the client side we need to handle this scenario as well which I have done in my above code.

In this article I have showed how we can issue get request from C# client code for various scenarios.