How To Call Web API In Another Project From C#

Introduction

 
This article explains how to call a web API from another project using C# instead of making an Ajax call. I'm  creating a web API in MVC  in project1 and want to call this API in another project (like.MVC,Asp.net,.core etc) project but don't want to make any Ajax requests.
 
So let's see how to make a C# request for an Api Call.
 
Here I  am creating an API in MVC for getting  a statelist   in Project 1.
  1.  public class StateController : ApiController  
  2.    {  
  3. [HttpGet]  
  4.        [Route("api/State/StateList")]  
  5.        public List<StateDto> StateList()  
  6.        {  
  7.            List<StateDto> StateList = new List<StateDto>();  
  8.            SqlConnection sqlConnection = new SqlConnection();  
  9.   
  10.            string connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;  
  11.            SqlCommand sqlCommand = new SqlCommand();  
  12.            sqlConnection.ConnectionString = connectionString;  
  13.            sqlCommand.CommandType = CommandType.Text;  
  14.            sqlCommand.CommandText = "Select * From lststate where deletedbyid is null";  
  15.            sqlCommand.Connection = sqlConnection;  
  16.            sqlConnection.Open();  
  17.            DataTable dataTable = new DataTable();  
  18.            dataTable.Load(sqlCommand.ExecuteReader());  
  19.            sqlConnection.Close();  
  20.   
  21.            if (dataTable != null)  
  22.            {  
  23.                foreach (DataRow row in dataTable.Rows)  
  24.                {  
  25.                    StateList.Add(new StateDto  
  26.                    {  
  27.                        Id = (int)row["id"],  
  28.                        StateCode = row["Statecode"].ToString(),  
  29.                        StateName = row["StateName"].ToString(),  
  30.                        CompanyId = (int)row["Companyid"],  
  31.                        CreatedDate = (DateTime)row["CreatedDate"]  
  32.                    });  
  33.   
  34.                }  
  35.                return StateList;  
  36.            }  
  37.            else  
  38.            {  
  39.   
  40.            }  
  41.   
  42.   
  43.        }  
Project 2 where we want to call this API.
  1. public List<StateDto> StateIndex()  
  2.   {  
  3.       var responseString = ApiCall.GetApi("http://localhost:58087/api/State/StateList");  
  4.       var rootobject = new JavaScriptSerializer().Deserialize<List<StateDto>>(responseString);  
  5.       return rootobject;  
  6.   }  
ApiCall.cs class  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Text;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace MaheApi.Dto  
  10. {  
  11.     public static class ApiCall  
  12.     {  
  13.         public static string GetApi(string ApiUrl)  
  14.         {  
  15.   
  16.             var responseString = "";  
  17.             var request = (HttpWebRequest)WebRequest.Create(ApiUrl);  
  18.             request.Method = "GET";  
  19.             request.ContentType = "application/json";  
  20.   
  21.             using (var response1 = request.GetResponse())  
  22.             {  
  23.                 using (var reader = new StreamReader(response1.GetResponseStream()))  
  24.                 {  
  25.                     responseString = reader.ReadToEnd();  
  26.                 }  
  27.             }  
  28.             return responseString;  
  29.   
  30.         }  
  31.   
  32.   
  33.   
  34.         public static string PostApi(string ApiUrl, string postData = "")  
  35.         {  
  36.   
  37.             var request = (HttpWebRequest)WebRequest.Create(ApiUrl);  
  38.             var data = Encoding.ASCII.GetBytes(postData);  
  39.             request.Method = "POST";  
  40.             request.ContentType = "application/x-www-form-urlencoded";  
  41.             request.ContentLength = data.Length;  
  42.             using (var stream = request.GetRequestStream())  
  43.             {  
  44.                 stream.Write(data, 0, data.Length);  
  45.             }  
  46.             var response = (HttpWebResponse)request.GetResponse();  
  47.             var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();  
  48.             return responseString;  
  49.         }  
  50.   
  51.   
  52.   
  53.      
  54.   
  55.   
  56.     }  
  57. }  
Output
 
Here we get data in StateIndex method..