Consume Web API in .NET Core MVC using HTTPClient

 NET


In this blog will create a database and create Web API and connect web API to database and fetch records. Finally create mvc project to consume the web API. we are doing this in visual studio 2017 using .NET Core version 2.1.

This blog we will divide into  steps.

Step1: In SQL Server create database and table and insert some records in it.

Step2: Create new project for Web API. connect to database using Entity Framework Core.

Step3: Create new project for .NET Core Application and consume Web API.

Step1: In SQL Server Create database and table and insert some records in it.

will open SQL server and execute the below script. this script will create a database named TestDB in SQL server and then create a table named Users.

Script:

create database TestDB

GO

create table Users(

Id int identity primary key,

UserName varchar(100),

Mobile varchar(100),

Age varchar(10)

)

insert into Users values ('Name1','091203801','21'),

('Name2','0908091','22'),

('Name3','0908091','23')


Step2: Create new project for Web API. connect to database using Entity Framework Core.

a. Create a new project in visual studio.
CORE
b. Create ASP.NET Core Web ApplicationWeb
c. select API and click OK.
API

d. we can see the project got created.
HTTP

e. Open Solution Explorer:

Client


f. Run the application we can see the URL:

visual studio will create values controller in default. and display as above.

https://localhost:44345/api/values

image10

g. Go to appsettings.json and add connection string to connect to database.

with windows Authentication:

"ConnectionStrings": {

    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=TestDB;MultipleActiveResultSets=true;Integrated Security=True;"

  }

with username and password:

"ConnectionStrings": {

    "DefaultConnection": "Server=ServerName;Initial Catalog=DatabaseName;MultipleActiveResultSets=true;User ID=UserName;Password=Userpassword"

  }

MVC

h. Add Models folder and add TestDbContext class to it.
image9

i. We Need Microsoft.entityframework core for entity models to connect to database.

go to NuGet Package and add Microsoft.EntityFramework Core


Consume web API

image11

select project and click install. Please select the version based on your compatibility .NET Core Version.

image12

image13
j. After successful installation open testdbcontext class.
 add code as below.
image15

k. Add a class in model folder same as your Table Name. Users class added models folder.
image17

Add Users Table class to DbContext class as below.
image19


l. Add new Controller Named UserController 
image19
m. select API Controller-Empty and click Add.
image20

image21
n. Replace your UserController with the below code.

image22
Code:
        private readonly TestDBContext _context;

        public UserController(TestDBContext context)
        {
            _context = context;
        }

        // GET: api/Users
        [HttpGet]
        [Route("GetUsers")]
        public async Task<ActionResult<IEnumerable<Users>>> GetUsers()
        {
            return await _context.Users.ToListAsync();
        }

We need to configure the dbcontext service in startup class.

o. Go to Startup class
 and open  ConfigureServices method.

replace as below.
image2212


p. Now run the project and open the url as below with your port number

https://localhost:44345/api/user/getusers


image23


In browser we can see json formatted table data from database.
Now you finally created a WebAPI using Entity Framework Core.

Step3: Create new Web Application Core and consume Web API

a. Create new project with asp.net Core Application with MVC selected as below.
web

b. After successful creation your solution structure looks like below.
image25


c. Create a new class in Models folder as Users.
Image26


d. Add WebBaseUrl key in appsettings.json.
image27
e. Create new MVC Controller-Empty with name UserController.
image29

f. Add View on right click beside the View() and add index view and select the model class as Users and Template as List.

Image30



g.It will create a Index.cshtml as below.
Image31


h. Then write the code to fetch data from the API using HttpClient. Replace UserController with following Code.

Image32

For easy replacement I pasted Controller Code here.

public class UserController : Controller
    {
        private readonly IConfiguration _Configure;
        private readonly string apiBaseUrl;
        public UserController(IConfiguration configuration)
        {
            _Configure = configuration;
            apiBaseUrl = _Configure.GetValue<string>("WebBaseUrl");
        }
        public IActionResult Index()
        {
            using (HttpClient client = new HttpClient())
            {               
                string endpoint = apiBaseUrl + "User/GetUsers";
                var Response = client.GetAsync(endpoint).Result;
                if (Response.IsSuccessStatusCode)
                {
                    var result = JsonConvert.DeserializeObject<List<Users>>(Response.Content.ReadAsStringAsync().Result);
                    return View(result);
                }                
                return View();
            }
        }
    }

l. Run the application and open below url. Here User is controller name.

https://localhost:44382/user

Image33



Finally we completed our 3rd step consuming Web API in .Net Core application.

Post a Comment

0 Comments