In this post we will discuss how to create CRUD API in ASP.NET Core Web API project with My SQL 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 dbo.department( DepartmentId int AUTO_INCREMENT, DepartmentName nvarchar(500), PRIMARY KEY (DepartmentId) )
Lets insert some records using insert query.
INSERT into dbo.Department (DepartmentName) VALUES ('IT') INSERT into dbo.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 dbo.Employee( EmployeeId int AUTO_INCREMENT, EmployeeName nvarchar(500), Department nvarchar(500), DateOfJoining datetime, PhotoFileName nvarchar(500), PRIMARY KEY(EmployeeId) ); insert into dbo.Employee(EmployeeName,Department,DateOfJoining,PhotoFileName) values ('Bob','IT','2021-06-21','anonymous.png'); select * from dbo.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 MySQL server, please also add below nuget package (MySQL Client).
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 MySql.Data.MySqlClient; 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,DepartmentName from dbo.Department "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); MySqlDataReader myReader; using(MySqlConnection mycon=new MySqlConnection(sqlDataSource)) { mycon.Open(); using(MySqlCommand myCommand=new MySqlCommand(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 dbo.Department (DepartmentName) values (@DepartmentName); "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); MySqlDataReader myReader; using (MySqlConnection mycon = new MySqlConnection(sqlDataSource)) { mycon.Open(); using (MySqlCommand myCommand = new MySqlCommand(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 dbo.Department set DepartmentName =@DepartmentName where DepartmentId=@DepartmentId; "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); MySqlDataReader myReader; using (MySqlConnection mycon = new MySqlConnection(sqlDataSource)) { mycon.Open(); using (MySqlCommand myCommand = new MySqlCommand(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 dbo.Department where DepartmentId=@DepartmentId; "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); MySqlDataReader myReader; using (MySqlConnection mycon = new MySqlConnection(sqlDataSource)) { mycon.Open(); using (MySqlCommand myCommand = new MySqlCommand(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 MySql.Data.MySqlClient; 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,EmployeeName,Department, DATE_FORMAT(DateOfJoining,'%Y-%m-%d') as DateOfJoining, PhotoFileName from dbo.Employee "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); MySqlDataReader myReader; using (MySqlConnection mycon = new MySqlConnection(sqlDataSource)) { mycon.Open(); using (MySqlCommand myCommand = new MySqlCommand(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 dbo.Employee (EmployeeName,Department,DateOfJoining,PhotoFileName) values (@EmployeeName,@Department,@DateOfJoining,@PhotoFileName) ; "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); MySqlDataReader myReader; using (MySqlConnection mycon = new MySqlConnection(sqlDataSource)) { mycon.Open(); using (MySqlCommand myCommand = new MySqlCommand(query, mycon)) { myCommand.Parameters.AddWithValue("@EmployeeName", emp.EmployeeName); myCommand.Parameters.AddWithValue("@Department", emp.Department); myCommand.Parameters.AddWithValue("@DateOfJoining", 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 dbo.Employee set EmployeeName =@EmployeeName, Department =@Department, DateOfJoining =@DateOfJoining, PhotoFileName =@PhotoFileName where EmployeeId=@EmployeeId; "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); MySqlDataReader myReader; using (MySqlConnection mycon = new MySqlConnection(sqlDataSource)) { mycon.Open(); using (MySqlCommand myCommand = new MySqlCommand(query, mycon)) { myCommand.Parameters.AddWithValue("@EmployeeId", emp.EmployeeId); myCommand.Parameters.AddWithValue("@EmployeeName", emp.EmployeeName); myCommand.Parameters.AddWithValue("@Department", emp.Department); myCommand.Parameters.AddWithValue("@DateOfJoining", 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 dbo.Employee where EmployeeId=@EmployeeId; "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon"); MySqlDataReader myReader; using (MySqlConnection mycon = new MySqlConnection(sqlDataSource)) { mycon.Open(); using (MySqlCommand myCommand = new MySqlCommand(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 httpReuest = Request.Form; var postedFile = httpReuest.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"); } } } }
hi Mate while i tried to build this with local database it is saying it is not able to reach the server can you please help me with any idea to resolve
ReplyDeletecheck your connection string/if you have admin rights or go through similar error threads on stackoverflow
Deleteexcellent tutorial. thanks
ReplyDeleteI am having issue on setup new connection in mysql workbench. Can you please help?!
ReplyDelete