How To Create .Net Core API 2
How To Create .Net Core API 2
Name the solution MyProject > Choose the Location of your project > click Create button
Click File > Add > New Project
Search for API > Select ASP.NET Code Web API > Click Next
Under Properties folder > Edit launchSettings.json > change Port number to 5010
Open appsettings.json > add the ConnectionString
Sample Connection String value (Update the values based on your Server/Database)
"ConnectionStrings": {
"SampleDatabase":
"Server=MyServerName\\SQLEXPRESS;Database=Sample;Trusted_Connection=True;TrustServerCertificate=true;"
}
Go to Tools > Nuget Package Manager > Manager Nuget Packager for Solution...
Right-click on Solution name MyProject > click Add > click New Folder
Create new folder named as Data
using Microsoft.EntityFrameworkCore;
using MyProject.Api.Data.Entity;
namespace MyProject.Api.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
namespace MyProject.Api.Data.Entity
{
public class Student
{
public long Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public int Age { get; set; }
}
}
update dbo.Students
set Name = @Name,
Email = @Email,
Phone = @Phone,
Age = @Age
where Id = @Id
GO
Select “API Controller with actions, using Entity Framework” > click Add
Select or Enter the following then click Add
Model class: Student
DBContext Class: AppDbContext
Controllner Name: StudentController
By this time, you can Run and Test the API application. Press F5
If Student table contain records, result would show on Response Body section (see below)
ENDPOINT PURPOSE
GET /api/Students Get all records
POST /api/Students Add record
GET /api/Students/{Id} Get record by specific Id
PUT /api/Students/{Id} Edit record
DELETE /api/Students/{Id} Delete record
You can also try the above APIs on POSTMAN (see below for sample postman requests):
Next Steps is to Convert the pre-generated controller methods to connect or use
Stored Procedures
Before doing the succeeding steps, your should have already created the Stored Procedures
below on your database:
[dbo].[sp_AddStudent]
[dbo].[sp_DeleteStudent]
[dbo].[sp_EditStudent]
[dbo].[sp_getStudents]
[dbo].[sp_getStudentsById]
Open StudensController.cs
FROM:
// GET: api/Students
[HttpGet]
public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
{
return await _context.Students.ToListAsync();
}
TO:
// GET: api/Students
[HttpGet]
public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
{
string sqlQuery = "exec dbo.sp_getStudents";
var data = await _context.Students.FromSql(FormattableStringFactory.Create(sqlQuery)).ToListAsync();
if (data == null)
{
return NotFound();
}
return Ok(data);
}
FROM:
// GET: api/Students/5
[HttpGet("{id}")]
public async Task<ActionResult<Student>> GetStudent(long id)
{
var student = await _context.Students.FindAsync(id);
if (student == null)
{
return NotFound();
}
return student;
}
TO:
// GET: api/Students/5
[HttpGet("{id}")]
public async Task<ActionResult<Student>> GetStudent(long id)
{
string sqlQuery = "exec dbo.sp_getStudentsById @Id";
SqlParameter parameter = new SqlParameter("@Id", id);
var data = await _context.Students.FromSqlRaw(sqlQuery, parameter).ToListAsync();
if (data == null)
{
return NotFound();
}
FROM:
// PUT: api/Students/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutStudent(long id, Student student)
{
if (id != student.Id)
{
return BadRequest();
}
_context.Entry(student).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!StudentExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
TO:
// PUT: api/Students/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutStudent(long id, Student student)
{
if (id != student.Id)
{
return BadRequest();
}
return Ok(data);
}
FROM:
// POST: api/Students
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Student>> PostStudent(Student student)
{
_context.Students.Add(student);
await _context.SaveChangesAsync();
// POST: api/Students
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Student>> PostStudent(Student student)
{
string sqlQuery = "dbo.sp_AddStudent @Name, @Email, @Phone, @Age";
SqlParameter[] parameter = {
new SqlParameter("@Name", student.Name),
new SqlParameter("@Email", student.Email),
new SqlParameter("@Phone", student.Phone),
new SqlParameter("@Age", student.Age)
};
var data = await _context.Database.ExecuteSqlRawAsync(sqlQuery, parameter);
return Ok(data);
}
FROM:
// DELETE: api/Students/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteStudent(long id)
{
var student = await _context.Students.FindAsync(id);
if (student == null)
{
return NotFound();
}
_context.Students.Remove(student);
await _context.SaveChangesAsync();
return NoContent();
}
TO:
// DELETE: api/Students/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteStudent(long id)
{
string sqlQuery = "dbo.sp_DeleteStudent @Id";
SqlParameter parameter = new SqlParameter("@Id", id);
return Ok(data);
}