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.
b. Create ASP.NET Core Web Application
c. select API and click OK.
d. we can see the project got created.
e. Open Solution Explorer:
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
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"
}
h. Add Models folder and add TestDbContext class to it.
i. We Need Microsoft.entityframework core for entity models to connect to database.
go to NuGet Package and add Microsoft.EntityFramework Core
select project and click install. Please select the version based on your compatibility .NET Core Version.
j. After successful installation open testdbcontext class.
add code as below.
k. Add a class in model folder same as your Table Name. Users class added models folder.
Add Users Table class to DbContext class as below.
l. Add new Controller Named UserController
m. select
API Controller-Empty and click
Add.
n. Replace your UserController with the below code.
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.
p. Now run the project and open the url as below with your port number
https://localhost:44345/api/user/getusers
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.
b. After successful creation your solution structure looks like below.
c. Create a new class in Models folder as Users.
d. Add WebBaseUrl key in appsettings.json.
e. Create new MVC Controller-Empty with name UserController.
f. Add View on right click beside the View() and add index view and select the model class as Users and Template as List.
g.It will create a Index.cshtml as below.
h. Then write the code to fetch data from the API using HttpClient. Replace UserController with following Code.
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
Finally we completed our 3rd step consuming Web API in .Net Core application.
Post a Comment
0 Comments