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.
- public class StateController : ApiController
- {
- [HttpGet]
- [Route("api/State/StateList")]
- public List<StateDto> StateList()
- {
- List<StateDto> StateList = new List<StateDto>();
- SqlConnection sqlConnection = new SqlConnection();
- string connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
- SqlCommand sqlCommand = new SqlCommand();
- sqlConnection.ConnectionString = connectionString;
- sqlCommand.CommandType = CommandType.Text;
- sqlCommand.CommandText = "Select * From lststate where deletedbyid is null";
- sqlCommand.Connection = sqlConnection;
- sqlConnection.Open();
- DataTable dataTable = new DataTable();
- dataTable.Load(sqlCommand.ExecuteReader());
- sqlConnection.Close();
- if (dataTable != null)
- {
- foreach (DataRow row in dataTable.Rows)
- {
- StateList.Add(new StateDto
- {
- Id = (int)row["id"],
- StateCode = row["Statecode"].ToString(),
- StateName = row["StateName"].ToString(),
- CompanyId = (int)row["Companyid"],
- CreatedDate = (DateTime)row["CreatedDate"]
- });
- }
- return StateList;
- }
- else
- {
- }
- }
Project 2 where we want to call this API.


Mark EvansPosted Apr 14, 2022, 8:12 AM
Hi would you have similar examples for both PUT and DELETE in the ApiCall.cs file ?