In this post we will discuss how to create CRUD API in ASP.NET Core Web API project with PostgreSQL as the database.
Lets first create the database tables required for our app.
We need two tables for our app.
One to store department details and another one to store employee details.
Lets start with department table.
This table will have two fields.
One to store an auto incremented department id, and another one to store the department name.
create table Department(
DepartmentId serial,
DepartmentName varchar(500)
);
Lets insert some records using insert query.
insert into Department(DepartmentName) values ('IT');
insert into Department(DepartmentName) values ('Support');
Let us similarly create table to store employee details.
We will be storing employee id, employee name, department to which the employee belongs to, the date of joining and also the uploaded profile picture file name.
create table Employee( EmployeeId serial, EmployeeName varchar(500), Department varchar(500), DateOfJoining date, PhotoFileName varchar(500) ); insert into Employee (EmployeeName,Department,DateOfJoining,PhotoFileName) values ('Bob', 'IT','2021-06-21','anonymous.png'); select * from Employee;
Lets create the dot net core web API project.
-> Lets open up visual studio first.
-> Click on create a new project.
-> Choose ASP dot net core Web API .
->Choose appropriate folder.
->We might not need HTTPS for now.
Now lets take a look at some of the important files in the project.
-> All the dependencies and packages needed for our app can be found in the dependencies folder.
-> launchSettings.json file contains the details of how the project should be started.
-> Controllers folders contains controllers in which we write our API methods.
-> We generally keep the configuration details such as database details in appSettings.json.
-> The program.cs contains the Main() program which is the entry point of our app.
-> Also it creates web host which basically helps the app to listen to http requests.
-> The startup class configures all the services needed for our app. Services are basically reusable components that can be used across our app using dependency
Injection. It also contains the configure method which creates our app’s request processing pipeline.
We need to make a couple of changes in startup class.
One is to enable the CORS.
By default, all web API projects come with a security which blocks requests coming from different domains. We are basically writing instructions to disable that security and allow the requests to be served.
We are also making one more change to the serializer class to keep the json serializer as our default.
We might need to install a nuget package to do this.
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json.Serialization; using Microsoft.Extensions.FileProviders; using System.IO; namespace WebApplication1 { 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) { //Enable CORS services.AddCors(c => { c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); }); //JSON Serializer services.AddControllersWithViews().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore) .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //Enable CORS app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "Photos")), RequestPath = "/Photos" }); } } }
app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "Photos")), RequestPath = "/Photos" });
Please also add a folder with name 'Photos'.
To work with PostgreSQL server, please also add below nuget package (NpgSQL).
Next, add the models.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApplication1.Models { public class Department { public int DepartmentId { get; set; } public string DepartmentName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApplication1.Models { public class Employee { public int EmployeeId { get; set; } public string EmployeeName {get; set; } public string Department { get; set; } public string DateOfJoining { get; set; } public string PhotoFileName { get; set; } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Npgsql; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; using WebApplication1.Models; namespace WebApplication1.Controllers { [Route("api/[controller]")] [ApiController] public class DepartmentController : ControllerBase { private readonly IConfiguration _configuration; public DepartmentController(IConfiguration configuration) { _configuration = configuration; } [HttpGet] public JsonResult Get() { string query = @" select DepartmentId as ""DepartmentId"", DepartmentName as ""DepartmentName"" from Department "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); NpgsqlDataReader myReader; using (NpgsqlConnection myCon = new NpgsqlConnection(sqlDataSource)) { myCon.Open(); using (NpgsqlCommand myCommand = new NpgsqlCommand(query, myCon)) { myReader = myCommand.ExecuteReader(); table.Load(myReader); myReader.Close(); myCon.Close(); } } return new JsonResult(table); } [HttpPost] public JsonResult Post(Department dep) { string query = @" insert into Department(DepartmentName) values (@DepartmentName) "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); NpgsqlDataReader myReader; using (NpgsqlConnection myCon = new NpgsqlConnection(sqlDataSource)) { myCon.Open(); using (NpgsqlCommand myCommand = new NpgsqlCommand(query, myCon)) { myCommand.Parameters.AddWithValue("@DepartmentName", dep.DepartmentName); myReader = myCommand.ExecuteReader(); table.Load(myReader); myReader.Close(); myCon.Close(); } } return new JsonResult("Added Successfully"); } [HttpPut] public JsonResult Put(Department dep) { string query = @" update Department set DepartmentName = @DepartmentName where DepartmentId=@DepartmentId "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); NpgsqlDataReader myReader; using (NpgsqlConnection myCon = new NpgsqlConnection(sqlDataSource)) { myCon.Open(); using (NpgsqlCommand myCommand = new NpgsqlCommand(query, myCon)) { myCommand.Parameters.AddWithValue("@DepartmentId", dep.DepartmentId); myCommand.Parameters.AddWithValue("@DepartmentName", dep.DepartmentName); myReader = myCommand.ExecuteReader(); table.Load(myReader); myReader.Close(); myCon.Close(); } } return new JsonResult("Updated Successfully"); } [HttpDelete("{id}")] public JsonResult Delete(int id) { string query = @" delete from Department where DepartmentId=@DepartmentId "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); NpgsqlDataReader myReader; using (NpgsqlConnection myCon = new NpgsqlConnection(sqlDataSource)) { myCon.Open(); using (NpgsqlCommand myCommand = new NpgsqlCommand(query, myCon)) { myCommand.Parameters.AddWithValue("@DepartmentId", id); myReader = myCommand.ExecuteReader(); table.Load(myReader); myReader.Close(); myCon.Close(); } } return new JsonResult("Deleted Successfully"); } } }
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Npgsql; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Threading.Tasks; using WebApplication1.Models; namespace WebApplication1.Controllers { [Route("api/[controller]")] [ApiController] public class EmployeeController : ControllerBase { private readonly IConfiguration _configuration; private readonly IWebHostEnvironment _env; public EmployeeController(IConfiguration configuration,IWebHostEnvironment env) { _configuration = configuration; _env = env; } [HttpGet] public JsonResult Get() { string query = @" select EmployeeId as ""EmployeeId"", EmployeeName as ""EmployeeName"", Department as ""Department"", to_char(DateOfJoining,'YYYY-MM-DD') as ""DateOfJoining"", PhotoFileName as ""PhotoFileName"" from Employee "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); NpgsqlDataReader myReader; using (NpgsqlConnection myCon = new NpgsqlConnection(sqlDataSource)) { myCon.Open(); using (NpgsqlCommand myCommand = new NpgsqlCommand(query, myCon)) { myReader = myCommand.ExecuteReader(); table.Load(myReader); myReader.Close(); myCon.Close(); } } return new JsonResult(table); } [HttpPost] public JsonResult Post(Employee emp) { string query = @" insert into Employee (EmployeeName,Department,DateOfJoining,PhotoFileName) values (@EmployeeName,@Department,@DateOfJoining,@PhotoFileName) "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); NpgsqlDataReader myReader; using (NpgsqlConnection myCon = new NpgsqlConnection(sqlDataSource)) { myCon.Open(); using (NpgsqlCommand myCommand = new NpgsqlCommand(query, myCon)) { myCommand.Parameters.AddWithValue("@EmployeeName", emp.EmployeeName); myCommand.Parameters.AddWithValue("@Department", emp.Department); myCommand.Parameters.AddWithValue("@DateOfJoining", Convert.ToDateTime(emp.DateOfJoining)); myCommand.Parameters.AddWithValue("@PhotoFileName", emp.PhotoFileName); myReader = myCommand.ExecuteReader(); table.Load(myReader); myReader.Close(); myCon.Close(); } } return new JsonResult("Added Successfully"); } [HttpPut] public JsonResult Put(Employee emp) { string query = @" update Employee set EmployeeName = @EmployeeName, Department = @Department, DateOfJoining = @DateOfJoining, PhotoFileName = @PhotoFileName where EmployeeId=@EmployeeId "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); NpgsqlDataReader myReader; using (NpgsqlConnection myCon = new NpgsqlConnection(sqlDataSource)) { myCon.Open(); using (NpgsqlCommand myCommand = new NpgsqlCommand(query, myCon)) { myCommand.Parameters.AddWithValue("@EmployeeId", emp.EmployeeId); myCommand.Parameters.AddWithValue("@EmployeeName", emp.EmployeeName); myCommand.Parameters.AddWithValue("@Department", emp.Department); myCommand.Parameters.AddWithValue("@DateOfJoining",Convert.ToDateTime(emp.DateOfJoining)); myCommand.Parameters.AddWithValue("@PhotoFileName", emp.PhotoFileName); myReader = myCommand.ExecuteReader(); table.Load(myReader); myReader.Close(); myCon.Close(); } } return new JsonResult("Updated Successfully"); } [HttpDelete("{id}")] public JsonResult Delete(int id) { string query = @" delete from Employee where EmployeeId=@EmployeeId "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); NpgsqlDataReader myReader; using (NpgsqlConnection myCon = new NpgsqlConnection(sqlDataSource)) { myCon.Open(); using (NpgsqlCommand myCommand = new NpgsqlCommand(query, myCon)) { myCommand.Parameters.AddWithValue("@EmployeeId", id); myReader = myCommand.ExecuteReader(); table.Load(myReader); myReader.Close(); myCon.Close(); } } return new JsonResult("Deleted Successfully"); } [Route("SaveFile")] [HttpPost] public JsonResult SaveFile() { try { var httpRequest = Request.Form; var postedFile = httpRequest.Files[0]; string filename = postedFile.FileName; var physicalPath = _env.ContentRootPath + "/Photos/" + filename; using(var stream=new FileStream(physicalPath, FileMode.Create)) { postedFile.CopyTo(stream); } return new JsonResult(filename); } catch (Exception) { return new JsonResult("anonymous.png"); } } } }
No comments:
Post a Comment