Follow us

Header Ads

Create WebApplication.API in Asp.Net Core

Create WebApplication.API in Asp.Net Core

Package

"Microsoft.EntityFrameworkCore" Version="5.0.0"
"Microsoft.EntityFrameworkCore.Design" Version="5.0.0"
"Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0" 

DataAccessLayer[Folder]

Employee.cs

using System;

namespace DataAccessLayer
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
    }
}

WebApplication.API[Folder]

Controllers[Folder]

EmployeesController.cs

using DataAccessLayer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication.API.Reposotories;

namespace WebApplication.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    //In Api Controller is inheritance with controller base class
    public class EmployeesController : Controller
    {
        private readonly IEmployeeRepository _employeeRepository;

        public EmployeesController(IEmployeeRepository employeeRepository)
        {
            _employeeRepository = employeeRepository;
        }
        //Get Employee from database
        [HttpGet]
        public async Task<ActionResult>GetEmployees()
        {
            try
            {
                return Ok(await _employeeRepository.GetEmployees());
            }
            catch (Exception)
            {
                //It can show 500 code internal error
                return StatusCode(StatusCodes.Status500InternalServerError, "Error in Retrieving Data from Database");
            }            
        }
        [HttpGet("{id:int}")]
        //Get Employee by Id 
        public async Task<ActionResult<Employee>> GetEmployees(int id)
        {
            try
            {
                var result = await _employeeRepository.GetEmployees(id);
                if(result==null)
                {
                    return NotFound();
                }
                return result;
            }
            catch (Exception)
            {
                //It can show 500 code internal error
                return StatusCode(StatusCodes.Status500InternalServerError, "Error in Retrieving Data from Database");
            }
        }
        //Insert data into database
        [HttpPost]
        public async Task<ActionResult<Employee>> CreateEmployees(Employee employee)
        {
            try
            {
                if (employee == null)
                {
                    return BadRequest();
                }
                var CreateEmployee = await _employeeRepository.AddEmployees(employee);
                return CreatedAtAction(nameof(GetEmployees), new { id = CreateEmployee.Id }, CreateEmployee);
            }
            catch (Exception)
            {
                //It can show 500 code internal error
                return StatusCode(StatusCodes.Status500InternalServerError, "Error in Retrieving Data from Database");
            }
        }
        //Update data from database
        [HttpPut("{id:int}")]
        public async Task<ActionResult<Employee>> UpdateEmployees(int id,Employee employee)
        {
            try
            {
                if(id!=employee.Id)
                {
                    return BadRequest("Id Mismatch");
                }
                var employeeUpdate = await _employeeRepository.GetEmployees(id);
                if (employeeUpdate == null)
                {
                    return NotFound($"Employee Id={id} not Found");
                }
                return await _employeeRepository.UpdateEmployees(employee);
            }
            catch (Exception)
            {
                //It can show 500 code internal error
                return StatusCode(StatusCodes.Status500InternalServerError, "Error in Retrieving Data from Database");
            }
        }
        //Delete data from database
        [HttpDelete("{id:int}")]
        public async Task<ActionResult<Employee>> DeleteEmployees(int id)
        {
            try
            {
                var employeeDelete = await _employeeRepository.GetEmployees(id);
                if (employeeDelete == null)
                {
                    return NotFound($"Employee Id={id} not Found");
                }
                return await _employeeRepository.DeleteEmployee(id);
            }
            catch (Exception)
            {
                //It can show 500 code internal error
                return StatusCode(StatusCodes.Status500InternalServerError, "Error in Retrieving Data from Database");
            }
        }
        //Search Data from Database
         //Use it https://localhost:44390/api/employees/Search?name=Amars for Search Data in Web Api
        [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 (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, "Error in Reterieving Data from Database");
            }
        }

    }

}

DataContext[Folder]

ApplicationDbContext.cs

using DataAccessLayer;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication.API.DataContext
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext>options):base(options)
        {
           
    }
        public DbSet<Employee> Employees { get; set; }
        //It is use for Sedding of Data after Database Created
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }
}

Reposotories[Folder]

EmployeeRepository.cs

using DataAccessLayer;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication.API.DataContext;

namespace WebApplication.API.Reposotories
{
    public class EmployeeRepository : IEmployeeRepository
    {
        private readonly ApplicationDbContext _Context;
        //Generate Constructor

        public EmployeeRepository(ApplicationDbContext context)
        {
            _Context = context;
        }

        //Select from Intelisence select Interface
        public async Task<Employee> AddEmployees(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>> GetEmployees()
        {
            return await _Context.Employees.ToListAsync();
        }

        public async Task<Employee> GetEmployees(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> UpdateEmployees(Employee employee)
        {
            var result = await _Context.Employees.FirstOrDefaultAsync(a => a.Id == employee.Id);
            if(result!=null)
            {
                result.Name = employee.Name;
                result.City = employee.City;
                await _Context.SaveChangesAsync();
                return result;
            }
            return null;
        }
    }
}

IEmployeeRepository.cs

using DataAccessLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication.API.Reposotories
{
   public interface IEmployeeRepository
    {
        //Add it for CRUD Operations in Web Api.
        Task<IEnumerable<Employee>> Search(string name);
        Task<IEnumerable<Employee>> GetEmployees();
        Task<Employee> GetEmployees(int Id);
        Task<Employee> AddEmployees(Employee employee);
        Task<Employee> UpdateEmployees(Employee employee);
        Task<Employee> DeleteEmployee(int Id);
    }
}

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=CHETUIWK1689\\MSSQL2019;Database=WebAPI;Trusted_Connection=True;MultipleActiveResultSets=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication.API.DataContext;
using WebApplication.API.Reposotories;

namespace WebApplication.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddScoped<IEmployeeRepository,EmployeeRepository>();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication.API", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication.API v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

WebApplication.Web[Folder]

launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:64316",
      "sslPort": 44397
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        //"ASPNETCORE_ENVIRONMENT": "Development"
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    },
    "WebApplication.Web": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Controllers[Folder]

HomeController.cs

using DataAccessLayer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using WebApplication.Web.Models;

namespace WebApplication.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
        //Not need of connection string and DbContext file because we can use only url for call api
        //Indexs() Action method is added for check exception
        public IActionResult Indexs()
        {
            throw new Exception("Error in Detail");
           // return view();
        }
        public async Task <IActionResult> Index()
        {
            List<Employee> employees = new List<Employee>();
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:60237");
            HttpResponseMessage response = await client.GetAsync("api/employees");
            if(response.IsSuccessStatusCode)
            {
                var results = response.Content.ReadAsStringAsync().Result;
                employees = JsonConvert.DeserializeObject<List<Employee>>(results);
            }
            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("http://localhost:60237");
            HttpResponseMessage response = await client.GetAsync($"api/employees/{id}");
            if (response.IsSuccessStatusCode)
            {
                var results = response.Content.ReadAsStringAsync().Result;
                employee = JsonConvert.DeserializeObject<Employee>(results);
            }

            return employee;
        }

        [HttpGet]

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public async Task <IActionResult> Create(Employee employee)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:60237");
            //Add Post for insert option
            var response = await client.PostAsJsonAsync<Employee>("api/employees/",employee);
            if(response.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
            return View();
        }
        public async Task<IActionResult> Delete(int id)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:60237");
            HttpResponseMessage response = await client.DeleteAsync($"api/employees/{id}");
            if (response.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
            return View();
        }
        [HttpGet]
        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("http://localhost:60237");
            //Add Put for Edit option
            var response = await client.PutAsJsonAsync<Employee>($"api/employees/{employee.Id}", employee);
            if (response.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
            return View();
        }
        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        //Error Action method is use for error controller
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Views[Folder]

Home

Create.cshtml

@model 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 type="hidden" 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="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");}
}

Detail.cshtml

@model 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>
        <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.PrimaryKey */ }) |
    <a asp-action="Index">Back to List</a>
</div>

Edit.cshtml

@model 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="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");}
}

Index.cshtml

@model IEnumerable<DataAccessLayer.Employee>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<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.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.City)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new {  id=item.Id }) |
                @Html.ActionLink("Detail", "Detail", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new {id=item.Id })
            </td>
        </tr>
}
    </tbody>
</table>



Post a Comment

0 Comments