Web API With HttpClient Or Consume Web API From Console Application

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 AngularJS, 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.

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

You can always download the source code here.

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 are not limited to that. Previously we used 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.

Firstly, we will create our Web API application.

Creating Web API application

Click File, New, then Project and then select MVC application. From the following pop up we will select the template as empty and select the core references and folders for MVC.

Empty Template With MVC And Web API Folders

Figure: 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

Figure: Folder Structure And References For Empty MVC Project

Using the code

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

Create a database

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

  1. USE [master]  
  2. GO  
  3. /****** Object: Database [TrialsDB]  
  4. CREATE DATABASE [TrialsDB]  
  5. CONTAINMENT = NONE  
  6. ON PRIMARY  
  7. NAME = N'TrialsDB', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  8. LOG ON  
  9. NAME = N'TrialsDB_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  10. GO  
  11. ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110  
  12. GO  
  13. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  14. begin  
  15. EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = 'enable'  
  16. end  
  17. GO  
  18. ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF  
  19. GO  
  20. ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF  
  21. GO  
  22. ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF  
  23. GO  
  24. ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF  
  25. GO  
  26. ALTER DATABASE [TrialsDB] SET ARITHABORT OFF  
  27. GO  
  28. ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF  
  29. GO  
  30. ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON  
  31. GO  
  32. ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF  
  33. GO  
  34. ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON  
  35. GO  
  36. ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF  
  37. GO  
  38. ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT GLOBAL  
  39. GO  
  40. ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF  
  41. GO  
  42. ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF  
  43. GO  
  44. ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF  
  45. GO  
  46. ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF  
  47. GO  
  48. ALTER DATABASE [TrialsDB] SET DISABLE_BROKER  
  49. GO  
  50. ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF  
  51. GO  
  52. ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF  
  53. GO  
  54. ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF  
  55. GO  
  56. ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF  
  57. GO  
  58. ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE  
  59. GO  
  60. ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF  
  61. GO  
  62. ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF  
  63. GO  
  64. ALTER DATABASE [TrialsDB] SET RECOVERY FULL  
  65. GO  
  66. ALTER DATABASE [TrialsDB] SET MULTI_USER  
  67. GO  
  68. ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM  
  69. GO  
  70. ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF  
  71. GO  
  72. ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )  
  73. GO  
  74. ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS  
  75. GO  
  76. ALTER DATABASE [TrialsDB] SET READ_WRITE  
  77. GO   

Now we will create the table we need. As of now I am going to create the tabletblTags

Create tables in database

Below is the query to create the tabletblTags.

  1. USE [TrialsDB]  
  2. GO  
  3. /****** Object: Table [dbo].[tblTags] Script Date: 23-Mar-16 5:01:22 PM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE TABLE [dbo].[tblTags](  
  9. [tagId] [int] IDENTITY(1,1) NOT NULL,  
  10. [tagName] [nvarchar](50) NOT NULL,  
  11. [tagDescription] [nvarchar](maxNULL,  
  12. CONSTRAINT [PK_tblTags] PRIMARY KEY CLUSTERED  
  13. (  
  14. [tagId] ASC  
  15. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  16. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  17. GO   

Can we insert some data to the tables now?

Insert data to table

You can use the below query to insert the data to the tabletblTags,

  1. USE[TrialsDB]  
  2. GO  
  3. INSERT INTO[dbo].[tblTags]  
  4.     ([tagName], [tagDescription])  
  5. VALUES( < tagName, nvarchar(50), > , < tagDescription, nvarchar(max), > )  
  6. GO   

Next thing we are going to do is creating a 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 process , 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 edmx extension have been created.

Now we 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, then select Web API 2 Controller with actions, using Entity Framework.

Web API 2 Controller With Actions Using Entity Framework

Figure: 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

Figure: Web API Controller With Async Actions

As you can see it has been given the name of our controller astblTags. 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.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Threading.Tasks;  
  10. using System.Web.Http;  
  11. using System.Web.Http.Description;  
  12. using WebAPIWithHttpClient.Models;  
  13. namespace WebAPIWithHttpClient.Controllers  
  14. {  
  15.     public class tblTagsController: ApiController  
  16.     {  
  17.         private TrialsDBEntities db = new TrialsDBEntities();  
  18.         // GET: api/tblTags  
  19.         public IQueryable < tblTag > GettblTags()  
  20.         {  
  21.             return db.tblTags;  
  22.         }  
  23.         // GET: api/tblTags/5  
  24.         [ResponseType(typeof(tblTag))]  
  25.         public async Task < IHttpActionResult > GettblTag(int id)  
  26.         {  
  27.             tblTag tblTag = await db.tblTags.FindAsync(id);  
  28.             if (tblTag == null)  
  29.             {  
  30.                 return NotFound();  
  31.             }  
  32.             return Ok(tblTag);  
  33.         }  
  34.         // PUT: api/tblTags/5  
  35.         [ResponseType(typeof(void))]  
  36.         public async Task < IHttpActionResult > PuttblTag(int id, tblTag tblTag)  
  37.         {  
  38.             if (!ModelState.IsValid)  
  39.             {  
  40.                 return BadRequest(ModelState);  
  41.             }  
  42.             if (id != tblTag.tagId)  
  43.             {  
  44.                 return BadRequest();  
  45.             }  
  46.             db.Entry(tblTag).State = EntityState.Modified;  
  47.             try  
  48.             {  
  49.                 await db.SaveChangesAsync();  
  50.             }  
  51.             catch (DbUpdateConcurrencyException)  
  52.             {  
  53.                 if (!tblTagExists(id))  
  54.                 {  
  55.                     return NotFound();  
  56.                 }  
  57.                 else  
  58.                 {  
  59.                     throw;  
  60.                 }  
  61.             }  
  62.             return StatusCode(HttpStatusCode.NoContent);  
  63.         }  
  64.         // POST: api/tblTags  
  65.         [ResponseType(typeof(tblTag))]  
  66.         public async Task < IHttpActionResult > PosttblTag(tblTag tblTag)  
  67.         {  
  68.             if (!ModelState.IsValid)  
  69.             {  
  70.                 return BadRequest(ModelState);  
  71.             }  
  72.             db.tblTags.Add(tblTag);  
  73.             await db.SaveChangesAsync();  
  74.             return CreatedAtRoute("DefaultApi"new  
  75.             {  
  76.                 id = tblTag.tagId  
  77.             }, tblTag);  
  78.         }  
  79.         // DELETE: api/tblTags/5  
  80.         [ResponseType(typeof(tblTag))]  
  81.         public async Task < IHttpActionResult > DeletetblTag(int id)  
  82.         {  
  83.             tblTag tblTag = await db.tblTags.FindAsync(id);  
  84.             if (tblTag == null)  
  85.             {  
  86.                 return NotFound();  
  87.             }  
  88.             db.tblTags.Remove(tblTag);  
  89.             await db.SaveChangesAsync();  
  90.             return Ok(tblTag);  
  91.         }  
  92.         protected override void Dispose(bool disposing)  
  93.         {  
  94.             if (disposing)  
  95.             {  
  96.                 db.Dispose();  
  97.             }  
  98.             base.Dispose(disposing);  
  99.         }  
  100.         private bool tblTagExists(int id)  
  101.         {  
  102.             return db.tblTags.Count(e => e.tagId == id) > 0;  
  103.         }  
  104.     }  
  105. }   

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

Figure: 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, then click Windows and then select Console application, Name your application, then click OK.

Console Application

Figure: Console Application

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

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace WebAPIWithHttpClientConsumer  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {}  
  11.     }  
  12.  

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

  1. public class tblTag  
  2. {  
  3.     public int tagId  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string tagName  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public string tagDescription  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18. }   

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

  1. using System.Net.Http;   

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

  1. HttpClient cons = new HttpClient();  
  2. cons.BaseAddress = new Uri("http://localhost:7967/");  
  3. cons.DefaultRequestHeaders.Accept.Clear();  
  4. cons.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));   

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

Get operation using HttpClient

  1. MyAPIGet(cons).Wait();   

The following is the definition of MyAPIGet function.

  1. static async Task MyAPIGet(HttpClient cons)  
  2. {  
  3.     using(cons)  
  4.     {  
  5.         HttpResponseMessage res = await cons.GetAsync("api/tblTags/2");  
  6.         res.EnsureSuccessStatusCode();  
  7.         if (res.IsSuccessStatusCode)  
  8.         {  
  9.             tblTag tag = await res.Content.ReadAsAsync < tblTag > ();  
  10.             Console.WriteLine("\n");  
  11.             Console.WriteLine("---------------------Calling Get Operation------------------------");  
  12.             Console.WriteLine("\n");  
  13.             Console.WriteLine("tagId tagName tagDescription");  
  14.             Console.WriteLine("-----------------------------------------------------------");  
  15.             Console.WriteLine("{0}\t{1}\t\t{2}", tag.tagId, tag.tagName, tag.tagDescription);  
  16.             Console.ReadLine();  
  17.         }  
  18.     }  
  19. }   

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 asyn call is success, the value inIsSuccessStatusCode 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 of theReadAsAsync is a part ofSystem.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, then click browse andsearch for System.Net.Http.Formatting.dll, click OK

Add References

Figure: Add References

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

Web_API_Consumer_Get_Output

Figure: Web_API_Consumer_Get_Output

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

Put operation using HttpClient

  1. static async Task MyAPIPut(HttpClient cons)  
  2. {  
  3.     using(cons)  
  4.     {  
  5.         HttpResponseMessage res = await cons.GetAsync("api/tblTags/2");  
  6.         res.EnsureSuccessStatusCode();  
  7.         if (res.IsSuccessStatusCode)  
  8.         {  
  9.             tblTag tag = await res.Content.ReadAsAsync < tblTag > ();  
  10.             tag.tagName = "New Tag";  
  11.             res = await cons.PutAsJsonAsync("api/tblTags/2", tag);  
  12.             Console.WriteLine("\n");  
  13.             Console.WriteLine("\n");  
  14.             Console.WriteLine("-----------------------------------------------------------");  
  15.             Console.WriteLine("------------------Calling Put Operation--------------------");  
  16.             Console.WriteLine("\n");  
  17.             Console.WriteLine("\n");  
  18.             Console.WriteLine("-----------------------------------------------------------");  
  19.             Console.WriteLine("tagId tagName tagDescription");  
  20.             Console.WriteLine("-----------------------------------------------------------");  
  21.             Console.WriteLine("{0}\t{1}\t\t{2}", tag.tagId, tag.tagName, tag.tagDescription);  
  22.             Console.WriteLine("\n");  
  23.             Console.WriteLine("\n");  
  24.             Console.WriteLine("-----------------------------------------------------------");  
  25.             Console.ReadLine();  
  26.         }  
  27.     }  
  28. } 

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

  1. tag.tagName = "New Tag";  
  2. res = await cons.PutAsJsonAsync("api/tblTags/2", tag);  

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

Web_API_Consumer_Put_Output

Figure: 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 delete operation below.

  1. async Task MyAPIDelete(HttpClient cons)  
  2. {  
  3.     using(cons)  
  4.     {  
  5.         HttpResponseMessage res = await cons.GetAsync("api/tblTags/2");  
  6.         res.EnsureSuccessStatusCode();  
  7.         if (res.IsSuccessStatusCode)  
  8.         {  
  9.             res = await cons.DeleteAsync("api/tblTags/2");  
  10.             Console.WriteLine("\n");  
  11.             Console.WriteLine("\n");  
  12.             Console.WriteLine("-----------------------------------------------------------");  
  13.             Console.WriteLine("------------------Calling Delete Operation--------------------");  
  14.             Console.WriteLine("------------------Deleted-------------------");  
  15.             Console.ReadLine();  
  16.         }  
  17.     }  
  18. }   

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

Web_API_Consumer_Delete_Output

Figure: 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.

  1. static async Task MyAPIPost(HttpClient cons)  
  2. {  
  3.     using(cons)  
  4.     {  
  5.         var tag = new tblTag  
  6.         {  
  7.             tagName = "jQuery", tagDescription = "This tag is all about jQuery"  
  8.         };  
  9.         HttpResponseMessage res = await cons.PostAsJsonAsync("api/tblTags", tag);  
  10.         res.EnsureSuccessStatusCode();  
  11.         if (res.IsSuccessStatusCode)  
  12.         {  
  13.             Console.WriteLine("\n");  
  14.             Console.WriteLine("\n");  
  15.             Console.WriteLine("-----------------------------------------------------------");  
  16.             Console.WriteLine("------------------Calling Post Operation--------------------");  
  17.             Console.WriteLine("------------------Created Successfully--------------------");  
  18.         }  
  19.     }  
  20. }   

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

  1. var tag = new tblTag { tagName = "jQuery", tagDescription = "This tag is all about jQuery" };  
  2. HttpResponseMessage res = await cons.PostAsJsonAsync("api/tblTags", tag);   

As you have noticed, I have not provided thetagId in the object, do yo know why? I have already setIdentity Specification with Identity Increment 1 in my tabletblTags in SQL database.

Now we will see the output. Shall we?

Web_API_Consumer_Post_Output

Figure: Web_API_Consumer_Post_Output

We have done everything! That’s fantastic, right? Happy coding.

You can always use WebClient also for this requirement, I will share that in 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 server itself or from any console application? Did you find this post useful? I hope you liked this article. Please share with 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.

Please see this article in my blog here.

Read more articles on ASP.NET:
 


Similar Articles