1. Pengantar ASP.NET Core 5
ASP.NET Core 5 adalah framework open-source yang dikembangkan oleh Microsoft untuk membangun aplikasi web modern, cepat, dan cross-platform. Framework ini menggabungkan kekuatan dari ASP.NET Core dengan fitur-fitur terbaru untuk pengembangan aplikasi web berbasis MVC (Model-View-Controller) dan API.
Dalam panduan ini, Anda akan belajar bagaimana membangun aplikasi web menggunakan ASP.NET Core 5 dengan pendekatan MVC dan mengelola data menggunakan Entity Framework Core.
2. Persiapan Lingkungan Pengembangan
Sebelum mulai coding, pastikan Anda sudah menyiapkan lingkungan pengembangan berikut:
-
Install
.NET 5 SDK
dari situs resmi Microsoft.
-
Editor kode seperti
Visual Studio 2019/2022
atau
Visual Studio Code
dengan ekstensi C#.
-
Database server seperti
SQL Server Express
atau
SQLite
untuk pengembangan lokal.
Setelah instalasi, verifikasi dengan menjalankan perintah berikut di terminal:
dotnet --version
Jika muncul versi .NET 5, maka instalasi berhasil.
3. Memahami Struktur MVC
MVC adalah pola desain yang memisahkan aplikasi menjadi tiga komponen utama:
-
Model:
Representasi data dan logika bisnis.
-
View:
Tampilan antarmuka pengguna.
-
Controller:
Penghubung antara Model dan View, mengatur alur aplikasi.
Struktur folder pada proyek ASP.NET Core MVC biasanya terdiri dari:
-
Controllers/
- berisi controller.
-
Models/
- berisi model data.
-
Views/
- berisi file tampilan Razor.
-
wwwroot/
- berisi file statis seperti CSS, JS, dan gambar.
4. Membuat Proyek ASP.NET Core 5 MVC
Untuk membuat proyek baru, buka terminal dan jalankan perintah berikut:
dotnet new mvc -n MyAspNetCoreApp
cd MyAspNetCoreApp
dotnet run
Perintah ini akan membuat proyek MVC baru bernama
MyAspNetCoreApp
dan menjalankan aplikasi di
https://localhost:5001
.
5. Routing dan Controller
Routing menentukan bagaimana URL dipetakan ke controller dan action. Contoh controller sederhana:
using Microsoft.AspNetCore.Mvc;
namespace MyAspNetCoreApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Halaman Tentang Kami";
return View();
}
}
}
URL
/Home/Index
akan memanggil method
Index
, dan
/Home/About
memanggil
About
.
6. Membuat Views dengan Razor
Views menggunakan Razor syntax untuk membuat tampilan dinamis. Contoh file
Views/Home/About.cshtml
:
@{
ViewData["Title"] = "Tentang Kami";
}
@ViewData["Title"]
@ViewData["Message"]
Razor memungkinkan Anda menyisipkan kode C# langsung di dalam HTML dengan sintaks
@
.
7. Model dan Validasi Data
Model merepresentasikan data aplikasi. Contoh model sederhana:
using System.ComponentModel.DataAnnotations;
namespace MyAspNetCoreApp.Models
{
public class Product
{
public int Id { get; set; }
[Required(ErrorMessage = "Nama produk wajib diisi")]
[StringLength(100)]
public string Name { get; set; }
[Range(0.01, 10000)]
public decimal Price { get; set; }
}
}
Data annotations seperti
[Required]
dan
[Range]
digunakan untuk validasi otomatis.
8. Entity Framework Core: Pengenalan dan Setup
Entity Framework Core (EF Core) adalah ORM (Object-Relational Mapper) yang memudahkan interaksi dengan database menggunakan model C#.
Untuk setup EF Core, tambahkan paket NuGet berikut:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Buat kelas
AppDbContext
untuk konfigurasi database:
using Microsoft.EntityFrameworkCore;
using MyAspNetCoreApp.Models;
namespace MyAspNetCoreApp.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Product> Products { get; set; }
}
}
9. Migrasi Database dan CRUD
Setelah konfigurasi DbContext, buat migrasi dan update database:
dotnet ef migrations add InitialCreate
dotnet ef database update
Contoh operasi CRUD di controller:
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyAspNetCoreApp.Data;
using MyAspNetCoreApp.Models;
using System.Threading.Tasks;
namespace MyAspNetCoreApp.Controllers
{
public class ProductsController : Controller
{
private readonly AppDbContext _context;
public ProductsController(AppDbContext context)
{
_context = context;
}
// GET: Products
public async Task<IActionResult> Index()
{
return View(await _context.Products.ToListAsync());
}
// GET: Products/Create
public IActionResult Create()
{
return View();
}
// POST: Products/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Product product)
{
if (ModelState.IsValid)
{
_context.Add(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(product);
}
}
}
10. Dependency Injection di ASP.NET Core
ASP.NET Core memiliki built-in dependency injection (DI) yang memudahkan pengelolaan service dan objek.
Contoh mendaftarkan DbContext di
Startup.cs
atau
Program.cs
:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Contoh service custom
builder.Services.AddScoped<IProductService, ProductService>();
DI memungkinkan controller menerima dependensi melalui constructor injection.
11. Autentikasi dan Otorisasi
ASP.NET Core menyediakan sistem autentikasi dan otorisasi yang kuat. Contoh menambahkan autentikasi cookie:
builder.Services.AddAuthentication("MyCookieAuth")
.AddCookie("MyCookieAuth", options =>
{
options.Cookie.Name = "MyCookieAuth";
options.LoginPath = "/Account/Login";
});
app.UseAuthentication();
app.UseAuthorization();
Gunakan atribut
[Authorize]
pada controller atau action untuk membatasi akses.
12. Deploy Aplikasi ASP.NET Core 5
Setelah aplikasi selesai, Anda bisa melakukan deploy ke berbagai platform seperti IIS, Azure, atau Linux server.
Contoh publish aplikasi:
dotnet publish -c Release -o ./publish
Folder
publish
berisi file yang siap diupload ke server.
13. Sumber Belajar dan Source Code
Berikut beberapa sumber belajar dan channel yang direkomendasikan untuk memperdalam ASP.NET Core 5:
Anda juga dapat mengunduh source code contoh lengkap dari panduan ini di:
Download Source Code Lengkap