Consuming Web API In .Net Core 3.1 MVC

In this article, you will see how to consume Web API in .Net core 3.1 MVC. This article will help beginners who are new to API concepts. Let's explore consuming web API in .Net core 3.1 MVC using a simple example. 
 
To make the concept easier to understand, I created a real world  scenario. In this demo project, a simple login application is created using web API and it is consumed on .Net core MVC. 
 

Why do we need API's and what's the use of using API's in the project ?

 
API stands for Application Programming Interface -- just like the online web services that are used by the apps at the client-side to retrieve information. An API will hold the central logic of an application irrespective to the number of client applications utilizing it. 
 
In order to understand better, let's consider an example, where there are a number of apps that support different platforms. Each client application will have its own business logic which would enable it to connect directly to the database in order to manipulate the data. Hence, implementing any change to the client application will be  tough. In case of any update, it will be required to make changes to each and every app individually. To avoid this conflict, it's better to use a central API to manipulate the data. It will be easy to maintain and changes can be done in one place.
 
Let's begin the project.
 
In this demo project, a simple login application is created using web API and it is consumed on .Net core MVC. 
 

Create Web API Project

 
Create new web API project, New project--> Choose ASP.Net Core Web Application--> Choose API--> Click Create.
 
Consuming Web API In .Net Core 3.1 MVC
 

Create Login and Signup Tables in Database

 
In this project the stored procedure approach is used to manipulate the data in the database. Create procedure for login and signup as "SpLogin" and "SpSignup". Login procedure returns count, when the user exists in the login table. Signup procedure allows new users to create a new account or allows the user to register.
 

Create a Database class

 
Usually connection string values should be given in appsettings.json. In this project, a separate dataclass is used to help beginners understand.  
  1. public class DataClass  
  2.    {  
  3.        public static string Connection = "Server=*******;Database=WebApiDemo;Trusted_Connection=True;";  
  4.   
  5.        public static string Conn { get => Connection; }  
  6.   
  7.    }  

Create a model class for userinfo

 
In this project, users are allowed to login and signup. So I need basic user info like username, password and mail as userinfo in my user model class.  
  1. public class UserInfo  
  2.     {  
  3.         public string UserName { getset; }  
  4.         public string Password { getset; }  
  5.         public string Mail { getset; }  
  6.   
  7.     }   

Create a Data access class

 
In this project users are allowed to login or signup, hence creating a class for data access contains methods like login and signup as given below in the code. For an existing user, true is returned by the checklogin method. For a new user, Userinfo is added to the signup table by the signup method. Both the methods return bool. 
  1. public class Dataaccess
  2.     {  
  3.         string conn = DataClass.Connection;  
  4.   
  5. //Method for Login  
  6.         public bool CheckLogin(UserInfo user)  
  7.         {  
  8.  using (SqlConnection connection = new SqlConnection(conn))  
  9.             {  
  10.                 
  11.                 if ( string.IsNullOrWhiteSpace(user.UserName) || string.IsNullOrWhiteSpace(user.Password))  
  12.                 {  
  13.                     return false;  
  14.                 }  
  15.                 SqlCommand cmd = new SqlCommand("loginForm", connection);  
  16.                 cmd.CommandType = CommandType.StoredProcedure;  
  17.                 connection.Open();  
  18.                 cmd.Parameters.AddWithValue("@Username1", user.UserName);  
  19.                 cmd.Parameters.AddWithValue("@Password1", user.Password);  
  20.                 object read = cmd.ExecuteScalar();  
  21.                 int Var = Convert.ToInt32(read);  
  22.                 connection.Close();  
  23.                  return Var==1;  
  24.             }  
  25.               
  26.         }  
  27. // Method for SignUp  
  28.         public bool Signup(UserInfo User)  
  29.         {  
  30.             using (SqlConnection connection= new SqlConnection(conn))  
  31.             {  
  32.                 SqlCommand cmd = new SqlCommand("Signinform", connection);  
  33.                 cmd.CommandType = CommandType.StoredProcedure;  
  34.                  connection.Open();  
  35.                 cmd.Parameters.AddWithValue("@Username1", User.UserName);  
  36.                 cmd.Parameters.AddWithValue("@Password1", User.Password);  
  37.                 cmd.Parameters.AddWithValue("@Mail", User.Mail);  
  38.                 int  read= cmd.ExecuteNonQuery();  
  39.                 connection.Close();  
  40.                 return read == 1;  
  41.   
  42.             }  
  43.         }  
  44.     }  
  45. }  

Controller actions

 
In the code given below, both login and signup are performing post operation. It returns OK or Unauthorized status for login method and OK or conflict for signup method based on the dataaccess class returned. In this project demo, Post operation is performed multiple times in the same controller. In such a case we need to specify routes clearly as given below in the code, based on actions. 
  1.   [ApiController]  
  2.     [Route("[controller]")]  
  3.   
  4.     public class WeatherForecastController : ControllerBase  
  5.   
  6.     {  
  7.         [HttpPost("Login")]  
  8.         public ActionResult get(UserInfo user)  
  9.         {  
  10.             Dataaccess db = new Dataaccess();  
  11.             if (db.CheckLogin(user))  
  12.                 return Ok();  
  13.                 return Unauthorized();  
  14.   
  15.   }  
  16.         [HttpPost("SignUp")]  
  17.         public ActionResult Post(UserInfo user)  
  18.         {  
  19.             Database db = new Database();  
  20.              if (db.Signup(user))  
  21.                 return Ok();  
  22.   
  23.             return Conflict();  
  24.   
  25.         }  
  26. }  
Hence, we are done with the API part. In upcoming steps, we will discuss how to consume this API in .Net Core MVC.
 
Let's begin the project.
 
We will create a simple .Net core MVC  project for consuming  the web API created above.
 

Create a new Project

 
Create a new MVC project, New project--> Choose ASP.Net Core Web Application--> Choose  Web application(Model-View-Controller)--> Click Create.
 
Consuming Web API In .Net Core 3.1 MVC
 

Create a model class for userinfo

 
In this project, users are allowed to login and signup. So i need basic user info like username, password and mail as userinfo in my user model class.
  1. public class UserInfo  
  2.    {  
  3.        [Required]  
  4.        public string Username { getset; }  
  5.        [Required]  
  6.        public string Password { getset; }  
  7.        public string Mail { getset; }  
  8.    }   

WebAPI URL 

 
Specify a WebAPI URL in appsettings.json. The URL defines the Web API URL created above. It's the best approach to use this in appsetting.json, as it will help to replicate the project in multiple enviornment. 
  1. {  
  2.   "Logging": {  
  3.     "LogLevel": {  
  4.       "Default""Information",  
  5.       "Microsoft""Warning",  
  6.       "Microsoft.Hosting.Lifetime""Information"  
  7.     }  
  8.   },  
  9.   "WebAPIBaseUrl""https://localhost:44318/weatherforecast"  
  10. }  

Controller actions

 
The code given below explains the workings of API in MVC, endpoint defines the application based URL that is API URL. By using dependency injection, we are consuming the API URL given in the appsettings.json.
  1. // Dependency Injection  
  2.       public HomeController(ILogger<HomeController> logger, IConfiguration configuration)  
  3.       {  
  4.           _logger = logger;  
  5.           _Configure = configuration;  
  6.   
  7.           apiBaseUrl = _Configure.GetValue<string>("WebAPIBaseUrl");  
  8.       }  
Usually data needs to be serialized to json and then it needs to be deserialized while rendering to view.
  1. //redirection Page   
  2.       [HttpGet]  
  3.       public ActionResult Profile()  
  4.       {  
  5.           UserInfo user = JsonConvert.DeserializeObject<UserInfo>(Convert.ToString(TempData["Profile"]));  
  6.           return View(user);  
  7.       }  
The code given below allows user to login by consuming the web API login method given above. It checks the response from the API. Once the response is OK it will redirect to profile page else it will display error message as username or password is incorrect.
  1. // Method to Display Userlogin Page    
  2.         [HttpGet]  
  3.         public ActionResult Index()  
  4.         {  
  5.             UserInfo user = new UserInfo();  
  6.             return View(user);  
  7.         }  
  8.  // Method to authenticate user login   
  9.         [HttpPost]  
  10.         public async Task<IActionResult> Index(UserInfo user)  
  11.         {  
  12.                  using (HttpClient client = new HttpClient())  
  13.                 {  
  14.                     StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");  
  15.                 string endpoint = apiBaseUrl + "/login";  
  16.   
  17.                     using (var Response = await client.PostAsync(endpoint, content))  
  18.                     {  
  19.                         if (Response.StatusCode == System.Net.HttpStatusCode.OK)  
  20.                         {  
  21.                             TempData["Profile"] = JsonConvert.SerializeObject(user);  
  22.                           
  23.                             return RedirectToAction("Profile");  
  24.   
  25.                         }  
  26.                         else  
  27.                         {  
  28.                            ModelState.Clear();  
  29.                             ModelState.AddModelError(string.Empty, "Username or Password is Incorrect");  
  30.                             return View();  
  31.                           
  32.                         }  
  33.   
  34.                     }  
  35.  }  
The code given below allows user to signup by consuming the web API signup method given above. It checks the response from the API, and once the response is OK it will redirect to profile page, otherwise it will display error as username already exists if the same user registers again.
  1. // Method to display Displaying UserSignup Page    
  2.       [HttpGet]  
  3.       public ActionResult Signup()  
  4.       {  
  5.           UserInfo user = new UserInfo();  
  6.           return View(user);  
  7.       }  
  8.       //Method to Insert User Credentials to Database  
  9.       [HttpPost]  
  10.       public async Task<IActionResult> Signup(UserInfo user)  
  11.   
  12.       {  
  13.           List<UserInfo> list = new List<UserInfo>();  
  14.           using (HttpClient client = new HttpClient())  
  15.           {  
  16.               StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");  
  17.               string endpoint = apiBaseUrl + "/SignUp";  
  18.               using (var Response = await client.PostAsync(endpoint, content))  
  19.               {  
  20.                   if (Response.StatusCode == System.Net.HttpStatusCode.OK)  
  21.                   {  
  22.                       TempData["Profile"] = JsonConvert.SerializeObject(user);  
  23.                       return RedirectToAction("Index");  
  24.                   }  
  25.                   else if(Response.StatusCode == System.Net.HttpStatusCode.Conflict)  
  26.                   {  
  27.                       ModelState.Clear();  
  28.                       ModelState.AddModelError("Username""Username Already Exist");  
  29.                       return View();  
  30.                   }  
  31.                   else  
  32.                   {  
  33.                       return View();  
  34.                   }  
  35.               }  
  36.   
  37.           }  
  38.       }  
Output is obtained as given below. For a valid user who already exists in login table, after login they will be redirected to profile page where it contains user info like user name etc.
 
Consuming Web API In .Net Core 3.1 MVC
Consuming Web API In .Net Core 3.1 MVC
Once the new user signs up they are allowed to log in to the application and the details will be  inserted in the database. In the output screenshot, the user is registered using a sign up method and the user name will be inserted into the table.
 
Consuming Web API In .Net Core 3.1 MVC
 
Consuming Web API In .Net Core 3.1 MVC
 
In this article we discussed how to consume web API's in .Net core MVC. Thanks for reading.