Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

.NETASP.NETWeb API
Home›.NET›Web API With HttpClient Or Consume Web API From Console Application

Web API With HttpClient Or Consume Web API From Console Application

By SibeeshVenu
March 28, 2016
9105
8
Share:
Web API Controller With Async Actions

In this article, we are going to learn how we can call Web API using HttpClient. Normally we call a Web API either from a jQuery Ajax or from Angular JS right? Recently I came across a need of calling our Web API from the server-side itself. Here I am going to use two Visual Studio applications. One is our normal Web API application in which I have a Web API controller and actions, another one is a console application where I consume my Web API. Sounds good? I am using Visual Studio 2015. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below.

  • MVC Tips, Tricks, Blogs
  • Web API Tips, Tricks, Blogs

Now we will go and create our application. I hope you will like this.

Download the source code

You can always download the source code here.

  • Web API Application and Consumer

Background

We all use Web API in our applications to implement HTTP services. HTTP services are much simpler than ever if we use Web API. But the fact is, the benefits of a Web API is not limited to that. Previously we use WCF services instead of Web API, where we were working with endpoints and all. Here I am going to explain an important feature of a Web API that we can call Web API from our server itself instead of using an Ajax Call. That is pretty cool, right? Now we will create our application.

First, we will create our Web API application.

Creating Web API application

Click File-> New-> Project then select MVC application. We will select the template as empty from the following pop-up and select the core references and folders for MVC.

Empty Template With MVC And Web API Folders
Empty Template With MVC And Web API Folders

Once you click OK, a project with MVC like folder structure with core references will be created for you.

Folder Structure And References For Empty MVC Project
Folder Structure And References For Empty MVC Project

Using the code

We will set up our database first so that we can create an Entity Model for our application later.

Create a database

The following query can be used to create a database in your SQL Server.

Now we will create the table we needed. As of now, I am going to create the table tblTags

Create tables in the database

Below is the query to create the table tblTags.

Can we insert some data into the tables now?

Insert data to the table

You can use the below query to insert the data to the table tblTags

The next thing we are going to do is creating an ADO.NET Entity Data Model.

Create Entity Data Model

Right-click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the processes, you can see the edmx file and other files in your model folder. Here I gave Dashboard for our Entity data model name. Now you can see a file with an edmx extension has been created.
Now will create our Web API controller.

Create Web API Controller

To create a Web API controller, just right click on your controller folder and click Add -> Controller -> Select Web API 2 controller with actions, using Entity Framework.

Web API 2 Controller With Actions Using Entity Framework
Web API 2 Controller With Actions Using Entity Framework

Now select tblTag (WebAPIWithHttpClient.Models) as our Model class and TrialsDBEntities (WebAPIWithHttpClient.Models) as data context class. This time we will select controller with async actions.

Web API Controller With Async Actions
Web API Controller With Async Actions

As you can see It has been given the name of our controller as tblTags. Here I am not going to change that, if you wish to change, you can do that.

Now you will be given the following codes in our new Web API controller.

As you can see, we have actions for,

  • Get
  • Post
  • Put
  • Delete

So the coding part to fetch the data from the database is ready, now we need to check whether our Web API is ready for action!. To check that, you just need to run the URL http://localhost:7967/api/tbltags. Here tblTags is our Web API controller name. I hope you get the data as a result.

Web_API_Result
Web_API_Result

As of now, our Web API application is ready, and we have just tested whether it is working or not. Now we can move on to create a console application where we can consume this Web API with the help of HttpClient. So shall we do that?

Create Console Application To Consume Web API

To create a console application, Click File -> New -> Click Windows -> Select Console application -> Name your application -> OK

Console Application
Console Application

I hope now you have a class called Program. cs with the below codes.

Now we will start our coding, We will create a class called tblTag with some properties so that we can use those when we need them.

To get started using the class HttpClient, you must import the namespace as follows.

using System.Net.Http;

Once you have imported the namespaces, we will set our HttpClient and the properties as follows.

As you can see we are just giving the base address of our API and setting the response header. Now we will create an async action to get the data from our database by calling our Web API.

Get operation using HttpClient

MyAPIGet(cons).Wait();

Following is the definition of the MyAPIGet function.

Here res.EnsureSuccessStatusCode(); ensure that it throws errors if we get any. If you don’t need to throw the errors, please remove this line of code. If the async call is a success, the value in IsSuccessStatusCode will be true.

Now when you run the above code, there are chances to get an error as follows.

Error CS1061 ‘HttpContent’ does not contain a definition for ‘ReadAsAsync’ and no extension method ‘ReadAsAsync’ accepting a first argument of type ‘HttpContent’ could be found (are you missing a using directive or an assembly reference?)

This is just because the ReadAsAsync is a part of System.Net.Http.Formatting.dll which we have not added to our application as a reference yet. Now we will do that? Sounds OK?

Just right click on the references and click add reference -> Click browse -> search for System.Net.Http.Formatting.dll – Click OK

Add References
Add References

Please add Newtonsoft.Json also. Now let us run our project and see our output.

Web_API_Consumer_Get_Output
Web_API_Consumer_Get_Output

Now shall we create a function for updating the record? Yes, we are going to create a function with the ‘Put’ request. Please copy and paste the preceding code for that.

Put operation using HttpClient

As you can see, we are updating the record as below once we get the response from await cons.GetAsync(“api/tblTags/2”) .

Again, run your application and check whether the tag name has been changed to ‘New Tag’.

Web_API_Consumer_Put_Output
Web_API_Consumer_Put_Output

Now did you see that your tag name has been changed? If yes, we are ready to go for our next operation. Are you ready?

Delete operation using HttpClient

We will follow the same procedure for delete operation too. Please see the code for the delete operation below.

To delete a record we uses res = await cons.DeleteAsync(“api/tblTags/2”); method. Now run your application and see the result.

Web_API_Consumer_Delete_Output
Web_API_Consumer_Delete_Output

What action is pending now? Yes, it is Post.

Post-operation using HttpClient

Please add the below function to your project for the post-operation.

We are just creating a new tblTag and assign some values, once the object is ready we are calling the method PostAsJsonAsync as follows.

As you have noticed, I have not provided the tagId in the object, do you know why? I have already set Identity Specification with Identity Increment 1 in my table tblTags in the SQL database.

Now we will see the output. Shall we?

Web_API_Consumer_Post_Output
Web_API_Consumer_Post_Output

We have done everything!. That’s fantastic right? Have a happy coding.

You can always use WebClient also for this requirement, that I will share in an another article.

Conclusion

Did I miss anything that you may think is needed? Did you try Web API yet? Have you ever wanted to call a Web API from the server itself or any console application? Could you find this post useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Kindest Regards
Sibeesh Venu

TagsAspNetHttpClientMVCWeb APIWeb API And HttpClientWeb API In Console Application
Previous Article

Rule “Oracle JRE 7 Update 51 (64-bit) ...

Next Article

March 2016 Month Winner In C-Sharp Corner

0
Shares
  • 0
  • +
  • 0
  • 0
  • 0

SibeeshVenu

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

Related articles More from author

  • jQuery Datatable With Server Side Data
    .NETAngularWeb API

    jQuery Datatable With Server Side Data

    February 25, 2016
    By SibeeshVenu
  • Custom Deffered Grid Using MVC Web API And Angular JS Deferred Output
    .NETAngularWeb API

    Custom Deferred Grid Using MVC Web API And Angular JS

    February 29, 2016
    By SibeeshVenu
  • .NETMVC

    Create And Consume A User Control In MVC

    July 14, 2015
    By SibeeshVenu
  • .NETCodeProjectMVC

    Uploading and Downloading in MVC Step-by-Step

    June 14, 2015
    By SibeeshVenu
  • Web API With Angular JS Solution Explorer
    .NETAngularWeb API

    Web API With Angular JS

    February 11, 2016
    By SibeeshVenu
  • Add_References
    .NETASP.NETWeb API

    Caching In Web API

    March 24, 2016
    By SibeeshVenu
0

My book

Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

YouTube

MICROSOFT MVP (2016-2022)

profile for Sibeesh Venu - Microsoft MVP

Recent Posts

  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
  • Easily move data from one COSMOS DB to another
  • .NET 8 New and Efficient Way to Check IP is in Given IP Range
  • Async Client IP safelist for Dot NET
  • Post Messages to Microsoft Teams Using Python
  • Get Azure Blob Storage Blob Metadata Using PowerShell
  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
  • Integrate Azure App Insights in 1 Minute to .Net6 Application
  • Azure DevOps Service Connection with Multiple Azure Resource Group

Tags

Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
  • .NET
  • Achievements
  • ADO.NET
  • Android
  • Angular
  • Arduino
  • Article Of The Day
  • ASP.NET
  • Asp.Net Core
  • Automobile
  • Awards
  • Azure
  • Azure CDN
  • azure devops
  • Blockchain
  • Blog
  • Browser
  • C-Sharp Corner
  • C#
  • Career Advice
  • Code Snippets
  • CodeProject
  • Cognitive Services
  • Cosmos DB
  • CSS
  • CSS3
  • Data Factory
  • Database
  • Docker
  • Drawings
  • Drill Down Chart
  • English
  • Excel Programming
  • Exporting
  • Facebook
  • Fun
  • Gadgets
  • GitHub
  • GoPro
  • High Map
  • HighChart
  • How to
  • HTML
  • HTML5
  • Ignite UI
  • IIS
  • Interview
  • IoT
  • JavaScript
  • JQuery
  • jQuery UI
  • JQWidgets
  • JQX Grid
  • Json
  • Knockout JS
  • Linux
  • Machine Learning
  • Malayalam
  • Malayalam Poems
  • MDX Query
  • Microsoft
  • Microsoft ADOMD
  • Microsoft MVP
  • Microsoft Office
  • Microsoft Technologies
  • Microsoft Windows
  • Microsoft Windows Server
  • Mobile
  • MongoDB
  • Monthly Winners
  • MVC
  • MVC Grid
  • MySQL
  • News
  • Node JS
  • npm
  • Number Conversions
  • October 2015
  • Office 365
  • Office Development
  • One Plus
  • Outlook
  • Page
  • PHP
  • Poems
  • PowerShell
  • Products
  • Q&A
  • Raspberry PI
  • React
  • SEO
  • SharePoint
  • Skype
  • Social Media
  • Software
  • Spire.Doc
  • Spire.PDF
  • Spire.XLS
  • SQL
  • SQL Server
  • SSAS
  • SSMS
  • Storage In HTML5
  • Stories
  • Third Party Software Apps
  • Tips
  • Tools
  • Translator Text
  • Uncategorized
  • Unit Testing
  • UWP
  • VB.Net
  • Videos
  • Virtual Machine
  • Visual Studio
  • Visual Studio 2017
  • Wamp Server
  • Web API
  • Web Platform Installer
  • Webinars
  • WebMatrix
  • Windows 10
  • Windows 7
  • Windows 8.1
  • Wordpress
  • Writing

ABOUT ME

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

Contact Me

  • info@sibeeshpassion.com

Pages

  • About
  • Search
  • Privacy Policy
  • About
  • Search
  • Privacy Policy
© Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
Go to mobile version