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.
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.
public class DataClass
{
public static string Connection = "Server=*******;Database=WebApiDemo;Trusted_Connection=True;";
public static string Conn { get => Connection; }
}
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.
public class UserInfo
{
public string UserName { get; set; }
public string Password { get; set; }
public string Mail { get; set; }
}
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.
public class Dataaccess
{
string conn = DataClass.Connection;
//Method for Login
public bool CheckLogin(UserInfo user)
{
using (SqlConnection connection = new SqlConnection(conn))
{
if ( string.IsNullOrWhiteSpace(user.UserName) || string.IsNullOrWhiteSpace(user.Password))
{
return false;
}
SqlCommand cmd = new SqlCommand("loginForm", connection);
cmd.CommandType = CommandType.StoredProcedure;
connection.Open();
cmd.Parameters.AddWithValue("@Username1", user.UserName);
cmd.Parameters.AddWithValue("@Password1", user.Password);
object read = cmd.ExecuteScalar();
int Var = Convert.ToInt32(read);
connection.Close();
return Var==1;
}
}
// Method for SignUp
public bool Signup(UserInfo User)
{
using (SqlConnection connection= new SqlConnection(conn))
{
SqlCommand cmd = new SqlCommand("Signinform", connection);
cmd.CommandType = CommandType.StoredProcedure;
connection.Open();
cmd.Parameters.AddWithValue("@Username1", User.UserName);
cmd.Parameters.AddWithValue("@Password1", User.Password);
cmd.Parameters.AddWithValue("@Mail", User.Mail);
int read= cmd.ExecuteNonQuery();
connection.Close();
return read == 1;
}
}
}
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.
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpPost("Login")]
public ActionResult get(UserInfo user)
{
Dataaccess db = new Dataaccess();
if (db.CheckLogin(user))
return Ok();
return Unauthorized();
}
[HttpPost("SignUp")]
public ActionResult Post(UserInfo user)
{
Database db = new Database();
if (db.Signup(user))
return Ok();
return Conflict();
}
}
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.
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.
public class UserInfo
{
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
public string Mail { get; set; }
}
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.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"WebAPIBaseUrl": "https://localhost:44318/weatherforecast"
}
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.
// Dependency Injection
public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
{
_logger = logger;
_Configure = configuration;
apiBaseUrl = _Configure.GetValue<string>("WebAPIBaseUrl");
}
Usually data needs to be serialized to json and then it needs to be deserialized while rendering to view.
//redirection Page
[HttpGet]
public ActionResult Profile()
{
UserInfo user = JsonConvert.DeserializeObject<UserInfo>(Convert.ToString(TempData["Profile"]));
return View(user);
}
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.
// Method to Display Userlogin Page
[HttpGet]
public ActionResult Index()
{
UserInfo user = new UserInfo();
return View(user);
}
// Method to authenticate user login
[HttpPost]
public async Task<IActionResult> Index(UserInfo user)
{
using (HttpClient client = new HttpClient())
{
StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
string endpoint = apiBaseUrl + "/login";
using (var Response = await client.PostAsync(endpoint, content))
{
if (Response.StatusCode == System.Net.HttpStatusCode.OK)
{
TempData["Profile"] = JsonConvert.SerializeObject(user);
return RedirectToAction("Profile");
}
else
{
ModelState.Clear();
ModelState.AddModelError(string.Empty, "Username or Password is Incorrect");
return View();
}
}
}
}
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.
// Method to display Displaying UserSignup Page
[HttpGet]
public ActionResult Signup()
{
UserInfo user = new UserInfo();
return View(user);
}
//Method to Insert User Credentials to Database
[HttpPost]
public async Task<IActionResult> Signup(UserInfo user)
{
List<UserInfo> list = new List<UserInfo>();
using (HttpClient client = new HttpClient())
{
StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
string endpoint = apiBaseUrl + "/SignUp";
using (var Response = await client.PostAsync(endpoint, content))
{
if (Response.StatusCode == System.Net.HttpStatusCode.OK)
{
TempData["Profile"] = JsonConvert.SerializeObject(user);
return RedirectToAction("Index");
}
else if(Response.StatusCode == System.Net.HttpStatusCode.Conflict)
{
ModelState.Clear();
ModelState.AddModelError("Username", "Username Already Exist");
return View();
}
else
{
return View();
}
}
}
}
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.
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.
In this article, we discussed how to consume web API's in .Net core MVC. Thanks for reading.