How to Make Web API and Consume Web API in .net Core 6
WebAPI
Appsettings.json -- Add Connection String
"AllowedHosts": "*",
"ConnectionStrings": { "DefaultConnection": "Server=.;Database=DbWebAPI;Trusted_Connection=True;MultipleActiveResultSets=True" }
Add New Project DataAcessLayer and add new Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebAPI.DataAccessLayer
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string PhoneNo { get; set; }
public string City { get; set; }
}
}
Making Folder DataContext
Add New Class File -- ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using WebAPI.DataAccessLayer;
namespace WebAPI.DataContext
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{ }
public DbSet<Employee> Employees { get; set; }
}
}
Program.cs -- Add Code
using Microsoft.EntityFrameworkCore;
using WebAPI.DataContext;
using WebAPI.Repositories;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IEmployeeRepository, EmployeeRepository>();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Making New Folder -- Repositories --- Add New Interface -- IEmployeeRepository.cs
using WebAPI.DataAccessLayer;
namespace WebAPI.Repositories
{
public interface IEmployeeRepository
{
Task<IEnumerable<Employee>> GetEmployee();
Task<Employee> GetEmployee(int Id);
Task<Employee> AddEmployee(Employee employee);
Task<Employee> UpdateEmployee(Employee employee);
Task<Employee> DeleteEmployee(int Id);
Task<IEnumerable<Employee>> Search(string name);
}
}
Add New Class -- EmployeeRepository.cs
using Microsoft.EntityFrameworkCore;
using WebAPI.DataAccessLayer;
using WebAPI.DataContext;
namespace WebAPI.Repositories
{
public class EmployeeRepository : IEmployeeRepository
{
private readonly ApplicationDbContext _Context;
public EmployeeRepository(ApplicationDbContext Context)
{
_Context = Context;
}
public async Task<Employee> AddEmployee(Employee employee)
{
var result = await _Context.Employees.AddAsync(employee);
await _Context.SaveChangesAsync();
return result.Entity;
}
public async Task<Employee> DeleteEmployee(int Id)
{
var result = await _Context.Employees.Where(a => a.Id == Id).FirstOrDefaultAsync();
if (result != null)
{
_Context.Employees.Remove(result);
await _Context.SaveChangesAsync();
return result;
}
return null;
}
public async Task<IEnumerable<Employee>> GetEmployee()
{
return await _Context.Employees.ToListAsync();
}
public async Task<Employee> GetEmployee(int Id)
{
return await _Context.Employees.FirstOrDefaultAsync(a => a.Id == Id);
}
public async Task<IEnumerable<Employee>> Search(string name)
{
IQueryable<Employee> query = _Context.Employees;
if (!string.IsNullOrEmpty(name))
{
query = query.Where(a => a.Name.Contains(name));
}
return await query.ToListAsync();
}
public async Task<Employee> UpdateEmployee(Employee employee)
{
var result = await _Context.Employees.FirstOrDefaultAsync(a => a.Id == employee.Id);
if (result != null)
{
result.Name = employee.Name;
result.PhoneNo = employee.PhoneNo;
result.City = employee.City;
await _Context.SaveChangesAsync();
return result;
}
return null;
}
}
}
EmployeeController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebAPI.DataAccessLayer;
using WebAPI.Repositories;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeeController(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
[HttpGet]
public async Task<ActionResult> GetEmployee()
{
try
{
return Ok(await _employeeRepository.GetEmployee());
}
catch (System.Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error Retriving Data form Database");
}
}
[HttpGet("{id:int}")]
public async Task<ActionResult<Employee>> GetEmployee(int id)
{
try
{
var result = await _employeeRepository.GetEmployee(id);
if (result == null)
{
NotFound();
}
return result;
}
catch (System.Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error Retriving Data form Database");
}
}
[HttpPost]
public async Task<ActionResult<Employee>> CreateEmployee(Employee employee)
{
try
{
if (employee == null)
{
return BadRequest();
}
var createdEmployee = await _employeeRepository.AddEmployee(employee);
return CreatedAtAction(nameof(GetEmployee), new { id = createdEmployee.Id }, createdEmployee);
}
catch (System.Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error Retriving Data form Database");
}
}
[HttpPut("{id:int}")]
public async Task<ActionResult<Employee>> UpdateEmployee(int id, Employee employee)
{
try
{
if (id != employee.Id)
{
return BadRequest("Id Mismatch");
}
var empUpdate = await _employeeRepository.GetEmployee(id);
if (empUpdate == null)
{
return NotFound($"Employee Id={id} not Fount");
}
return await _employeeRepository.UpdateEmployee(employee);
}
catch (System.Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error Retriving Data form Database");
}
}
[HttpDelete("{id:int}")]
public async Task<ActionResult<Employee>> DeleteEmployee(int id)
{
try
{
var empDelete = await _employeeRepository.GetEmployee(id);
if (empDelete == null)
{
return NotFound($"Employee Id={id} not Fount");
}
return await _employeeRepository.DeleteEmployee(id);
}
catch (System.Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error Retriving Data form Database");
}
}
//https://localhost:5001/api/employee/search?name=rajesh
[HttpGet("{search}")]
public async Task<ActionResult<IEnumerable<Employee>>> Search(string name)
{
try
{
var result = await _employeeRepository.Search(name);
if (result.Any())
{
return Ok(result);
}
return NotFound();
}
catch (System.Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error Retriving Data form Database");
}
}
}
}
WebAPIWebsite
Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddMvc();
builder.Services.AddHttpClient();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
HomeController.cs
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WebAPI.DataAccessLayer;
using WebAPIWebsite.Models;
namespace WebAPIWebsite.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public async Task<IActionResult> Index()
{
List<Employee> employees = new List<Employee>();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:7046/");
HttpResponseMessage response = await client.GetAsync("api/employee");
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
employees = JsonConvert.DeserializeObject<List<Employee>>(result);
}
return View(employees);
}
public async Task<IActionResult> Detail(int id)
{
Employee employee = await GetEmployeeById(id);
return View(employee);
}
private static async Task<Employee> GetEmployeeById(int id)
{
Employee employee = new Employee();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:7046/");
HttpResponseMessage response = await client.GetAsync($"api/Employee/{id}");
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
employee = JsonConvert.DeserializeObject<Employee>(result);
}
return employee;
}
public async Task<IActionResult> Delete(int id)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:7046/");
HttpResponseMessage response = await client.DeleteAsync($"api/Employee/{id}");
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return View();
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Create(Employee employee)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:7046/");
var response = await client.PostAsJsonAsync<Employee>("api/Employee", employee);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return View();
}
public async Task<IActionResult> Edit(int id)
{
Employee employee = await GetEmployeeById(id);
return View(employee);
}
[HttpPost]
public async Task<IActionResult> Edit(Employee employee)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:7046/");
var response = await client.PutAsJsonAsync<Employee>($"api/Employee/{employee.Id}", employee);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Index.cshtml
@model IEnumerable<WebAPI.DataAccessLayer.Employee>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Id)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.PhoneNo)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.PhoneNo)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Detail", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</tbody>
</table>
Create.cshtml
@model WebAPI.DataAccessLayer.Employee
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Employee</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
@* <div class="form-group">
<label asp-for="Id" class="control-label"></label>
<input asp-for="Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>*@
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PhoneNo" class="control-label"></label>
<input asp-for="PhoneNo" class="form-control" />
<span asp-validation-for="PhoneNo" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="City" class="control-label"></label>
<input asp-for="City" class="form-control" />
<span asp-validation-for="City" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Edit.cshtml
@model WebAPI.DataAccessLayer.Employee
@{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>Employee</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Id" class="control-label"></label>
<input asp-for="Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PhoneNo" class="control-label"></label>
<input asp-for="PhoneNo" class="form-control" />
<span asp-validation-for="PhoneNo" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="City" class="control-label"></label>
<input asp-for="City" class="form-control" />
<span asp-validation-for="City" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Detail.cshtml
@model WebAPI.DataAccessLayer.Employee
@{
ViewData["Title"] = "Detail";
}
<h1>Detail</h1>
<div>
<h4>Employee</h4>
<hr />
<dl class="row">
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Id)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Id)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Name)
</dd>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.PhoneNo)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.City)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.City)
</dd>
</dl>
</div>
<div>
@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
<a asp-action="Index">Back to List</a>
</div>
Delete.cshtml
@model WebAPI.DataAccessLayer.Employee
@{
ViewData["Title"] = "Delete";
}
<h1>Delete</h1>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Employee</h4>
<hr />
<dl class="row">
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Id)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Id)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Name)
</dd>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.PhoneNo)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.City)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.City)
</dd>
</dl>
<form asp-action="Delete">
<input type="submit" value="Delete" class="btn btn-danger" /> |
<a asp-action="Index">Back to List</a>
</form>
</div>