How to create ASP.NET Core Web API with Azure MySQL Server.
Introduction
In this
article, we are going to discuss Asp.net Core Web Api.
We are going to cover:
- What is API?
- What is Web API?
- Why Web Api required?
- How to create Asp.net Core web API using .Net 3.1
Prerequisites
- .NET 3.1
- Visual Studio 2019
What is an API?
Basically, an API is a set of
routines, protocols, and tools developers use to build software applications
and to specify how software components should interact. In simple terms, an API
is a messenger that sends a request to a provider you want data from and then
delivers the response back to you. Think of an API as an intermediary that
allows two programs to talk to each other.
Why
is Web API required?
The user wants to access the
application from different devices like mobile, browser, Google devices, etc.
In this case, Web API can be useful.Different devices request to Web API
and Web API will respond in JSON format. Most of the devices are able to understand
JSON output.
Let’s see the below web Api Architecture diagram,
Web API is
mostly used for CRED (Create, Read, EDIT, DELETE) operations. It follows
HTTP verbs for these operations.
- HTTP GET – Read Operation
- HTTP POST – Create Operation
- HTTP PUT – Update Operation
- HTTP DELETE – Delete Operation
How
to create an Asp.Net core web API?
Follow the below steps to create your first Web API project,
1. Open Visual
Studio 2019 and create a new project.
2. Select the
“Asp.Net Core Web API” template and click on Next.
3. Provide Project name and location.
4. Select Target Framework and click on Create button.
5. Once project is create basic view in solution explore.
6. Next we need to create two folder with names Controllers and Models.
7. Need to install dependency from Genet packages.
MySql.Data.dll
Microsoft.AspNetCore.Mvc.NewtonsoftJson.dll
– version 3.1.10
8. To connect Mysql we need added server name,
user name and password in appsettings.json.
{
"ConnectionStrings": {
"EmployeeAppcon": "Data
Source=*****.mysql.database.azure.com;initial catalog=”DateBaseName”;User
id=******; Pwd=******"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
9. We need update Startup.cs with below code.
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
namespace createwebapiusingmysql
{
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.
// For more information on how to configure your application,
visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
// Need to add cors for webapi
services.AddCors(c =>
{
c.AddPolicy("AllowOrgin", options =>
options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
services.AddControllersWithViews().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore)
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver = new DefaultContractResolver());
// We need added controllers
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.UseEndpoints(endpoints =>
{
app.UseEndpoints(endpoints
=>
{
endpoints.MapControllers();
});
});
}
}
}
10. In the model folder, create a Product’s class to storage set and get property.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace createwebapiusingmysql.Models
{
public class Products
{
public int
categoryId { get; set; }
public int
ProductId { get; set; }
public string
ProductName { get; set; }
public string
ProductDescription { get; set; }
public string
ProductManual { get; set; }
public string
ProductSpecification { get; set; }
public string
ProductWarranty { get; set; }
public string
ProductFeatures { get; set; }
public string
ProductModel { get; set; }
public string
ProductCompany { get; set; }
public string
ProductPreview { get; set; }
public string
ProductAuthor { get; set; }
public string
createdBy { get; set; }
}
}
11. Next create products controller in control folder to write get and post methods.
12. Add below code productscontroll.cs
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;
namespace createwebapiusingmysql.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : Controller
{
private readonly IConfiguration _configuration;
public ProductsController(IConfiguration configuration)
{
_configuration = configuration;
}
// Get All
products from mysql table
[HttpGet]
public JsonResult Getproducts()
{
string query = @"select * from tableName;";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("EmployeeAppcon");
MySqlDataReader myReader;
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
mycon.Open();
using (MySqlCommand mycommond = new MySqlCommand(query, mycon))
{
myReader =
mycommond.ExecuteReader();
table.Load(myReader);
myReader.Close();
mycon.Close();
}
}
return new
JsonResult(table);
}
}
}
13. Next Need to create table in Mysql server in azure:
create
table databaseName.products(
ProductId
INT AUTO_INCREMENT PRIMARY KEY,
ProductName
nvarchar(50),
categoryid
int,
productDescription
nvarchar(500),
productManual
nvarchar(50),
productSpecification
nvarchar(500),
productWarranty
nvarchar(100),
productFeatures
nvarchar(100),
productModel
nvarchar(100),
productCompany
nvarchar(50),
productPreview
nvarchar(500),
productCreated
date,
productAuthor
nvarchar(100),
foreign
key (categoryid)
references
categories(categoryid)
);
14. Final result in postman.
15. Add new product in product table.
15.1 First we
need to create stored procedures in MySQL database.
15.2
Create
stored procedures with below MySql commands.
CREATE DEFINER=`ceeaadmin`@`%` PROCEDURE `Add_categorie_products`(
fcategoryid varchar(50),
fproductname varchar(50),
fproductDescription
varchar(500),
fproductManual varchar(500),
fproductSpecification
varchar(100),
fproductWarranty varchar(100),
fproductFeatures varchar(100),
fproductModel varchar(100),
fproductCompany varchar(50),
fproductPreview varchar(500),
fproductAuthor varchar(50)
)
BEGIN
DECLARE ProductId INT DEFAULT 0;
START TRANSACTION;
INSERT INTO
restapi.Products(ProductName,categoryid,productDescription,productManual,productSpecification,productWarranty,
productFeatures,productModel,productCompany,productPreview,productCreated,productAuthor)
VALUES(fproductname,fcategoryid,fproductDescription,fproductManual,fproductSpecification,fproductWarranty,
fproductFeatures,fproductModel,fproductCompany,fproductPreview,curdate(),fproductAuthor);
SET ProductId =
LAST_INSERT_ID();
COMMIT;
SET ProductId := (select
last_insert_id());
select categoryName,ProductId
from restapi.categories,restapi.products where categories.categoryid =
products.categoryid AND products.ProductId=ProductId;
END
15.3
Please
create [httppost] method and add below code in controller.
// To
Insert New record
[HttpPost]
public JsonResult Post(Products prd)
{
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("EmployeeAppcon");
MySqlDataReader myReader;
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
try
{
// To Insert
New record using storage process
using (MySqlCommand mycommond = new MySqlCommand("restapi.Add_categorie_products", mycon))
{
mycommond.CommandType =
CommandType.StoredProcedure;
mycommond.Parameters.AddWithValue("@fcategoryid",
prd.categoryId);
mycommond.Parameters.AddWithValue("@fproductname", prd.ProductName);
mycommond.Parameters.AddWithValue("@fproductDescription", prd.ProductDescription);
mycommond.Parameters.AddWithValue("@fproductManual", prd.ProductManual);
mycommond.Parameters.AddWithValue("@fproductSpecification", prd.ProductSpecification);
mycommond.Parameters.AddWithValue("@fproductWarranty", prd.ProductWarranty);
mycommond.Parameters.AddWithValue("@fproductFeatures", prd.ProductFeatures);
mycommond.Parameters.AddWithValue("@fproductModel", prd.ProductModel);
mycommond.Parameters.AddWithValue("@fproductCompany",
prd.ProductCompany);
mycommond.Parameters.AddWithValue("@fproductPreview", prd.ProductPreview);
mycommond.Parameters.AddWithValue("@fproductAuthor", prd.ProductAuthor);
mycon.Open();
myReader =
mycommond.ExecuteReader();
table.Load(myReader);
myReader.Close();
mycon.Close();
}
}
catch (Exception ex)
{
string x = ex.Message.ToString();
string error = ex.StackTrace.ToString();
}
}
return new
JsonResult(table);
}
15.4 Please use
below json format to insert product using postman.
{
"categoryid":"1",
"ProductName": "Hammers",
"productModel": "modelurl",
"productAuthor": "F1255RDS2792",
"productCompany": "BOSCH_TEST",
"productDescription": "BOSCH",
"productManual": "Washer is able to perform various drum actions or a combination of\ndifferent actions depending on th",
"productSpecification": "686 mm(L) x 767 mm(P) x 982 mm(H)\n",
"productWarranty": "Labor 2 Year / Parts 2 Year",
"productFeatures": "Good to user",
"productPreview": "imageurl"
}
16. To update product using post man.
16.1
Add below
code in product controller.
// To Update the record
[HttpPut("{id}")]
public JsonResult Put(int id, Products prd)
{
string query = @"update restapi.products set
ProductName =
@ProductName,
ProductDescription
= @ProductDescription,
productManual =
@ProductManual,
ProductModel =
@ProductModel,
ProductSpecification = @ProductSpecification,
ProductWarranty =
@ProductWarranty,
productFeatures
= @productFeatures,
productPreview
=@productPreview,
ProductCompany
= @ProductCompany,
ProductAuthor =
@ProductAuthor
where ProductId
=@ProductId;";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("EmployeeAppcon");
MySqlDataReader myReader;
try
{
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
mycon.Open();
using (MySqlCommand mycommond = new MySqlCommand(query, mycon))
{
mycommond.Parameters.AddWithValue("@ProductId", id);
mycommond.Parameters.AddWithValue("@ProductName", prd.ProductName);
mycommond.Parameters.AddWithValue("@ProductDescription",
prd.ProductDescription);
mycommond.Parameters.AddWithValue("@ProductManual", prd.ProductManual);
mycommond.Parameters.AddWithValue("@ProductModel", prd.ProductModel);
mycommond.Parameters.AddWithValue("@ProductSpecification", prd.ProductSpecification);
mycommond.Parameters.AddWithValue("@ProductWarranty", prd.ProductWarranty);
mycommond.Parameters.AddWithValue("@productFeatures",
prd.ProductFeatures);
mycommond.Parameters.AddWithValue("@productPreview", prd.ProductPreview);
mycommond.Parameters.AddWithValue("@ProductCompany", prd.ProductCompany);
mycommond.Parameters.AddWithValue("@ProductAuthor", prd.ProductAuthor);
//mycon.Open();
myReader =
mycommond.ExecuteReader();
table.Load(myReader);
myReader.Close();
mycon.Close();
}
}
}
catch (Exception ex)
{
string x = ex.Message.ToString();
string error = ex.StackTrace.ToString();
}
return new
JsonResult("Product Updated Sucessfully");
}
Reference links:
https://www.youtube.com/watch?v=Br8H-TuSSO8
Comments
Post a Comment