0% found this document useful (0 votes)
21 views

Exams Lectures

Uploaded by

Duc Le
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Exams Lectures

Uploaded by

Duc Le
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Complete Step-by-Step Guide: Login System

with a Database Connection in .NET Core


using MySQL
This guide provides a complete implementation of
a Login System with:
Login Page: HTML/C# Code
Database Creation Script (MySQL)
Admin Page: Display user accounts after
successful login
Step-by-Step Implementation in .NET Core
Step 1: Set Up the Environment
• Install Prerequisites:
• .NET SDK: Download.
• MySQL Server and MySQL Workbench.
• Visual Studio Code with the C# Extension.
• Create a New .NET Core Project:
• Use terminal
• dotnet new webapp -o LoginSystemApp
• cd LoginSystemApp
• Install Required NuGet Packages:
• Add Entity Framework Core and MySQL packages:
• dotnet add package Pomelo.EntityFrameworkCore.MySql --version 8.0.2
• dotnet add package Microsoft.EntityFrameworkCore --version 8.0.2
• dotnet add package Microsoft.EntityFrameworkCore.Tools --version 8.0.2
• dotnet add package Microsoft.EntityFrameworkCore.Design --version 8.0.2
Step 2: MySQL Database Creation Script

• Use the following SQL script to create a database and a


Users table:
-- Create the Database
CREATE DATABASE LoginAppDB;

-- Switch to the Database


USE LoginAppDB;

-- Create the Users Table


CREATE TABLE Users (
Id INT PRIMARY KEY AUTO_INCREMENT,
Username VARCHAR(50) NOT NULL,
Password VARCHAR(255) NOT NULL, -- Hashed Password
Role VARCHAR(20) NOT NULL -- Admin or User
);

-- Insert Admin and User Records


INSERT INTO Users (Username, Password, Role)
VALUES
('admin', SHA2('adminpassword', 256), 'Admin'),
('user1', SHA2('userpassword', 256), 'User');
Step 3: Configure the Database Connection

• Add the Connection String in appsettings.json:


{
"ConnectionStrings": {
"DefaultConnection":
"Server=localhost;Database=LoginAppDB;User=root;Password
=yourpassword;"
}
}
Set Up Entity Framework Core:

• Create a folder Data and add AppDbContext.cs

using Microsoft.EntityFrameworkCore;
using LoginSystemApp.Models;

public class AppDbContext : DbContext


{
public
AppDbContext(DbContextOptions<AppDbContext>
options) : base(options) { }

public DbSet<User> Users { get; set; }


}
using LoginSystemApp.Data;
Register the DbContext in Program.cs:
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


builder.Services.AddRazorPages();
builder.Services.AddDbContext<AppDbContext>(o
ptions =>
options.UseMySql(

builder.Configuration.GetConnectionString("Default
Connection"),
new MySqlServerVersion(new Version(8, 0,
31)) // Replace with your MySQL version
));

var app = builder.Build();

app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
Create the User Model:

• Create a folder Models and add a file User.cs

namespace LoginSystemApp.Models;

public class User


{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Role { get; set; }
}
Run Migrations and Update Database:

• Enable migrations and update the database:

dotnet ef migrations add InitialCreate


dotnet ef database update
@page
Step 4: Create the Login Page @model LoginModel
<!DOCTYPE html>
<html>
<head>
• Login Page UI (Pages/Login.cshtml):
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form method="post">
<label>Username:</label>
<input type="text" name="Username" required
<br />
<label>Password:</label>
<input type="password" name="Password" requ
<br />
<button type="submit">Login</button>
</form>
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
<p style="color: red;">@Model.ErrorMessage</
}
</body>
</html>
Login Page Logic (Pages/Login.cshtml.cs):

public IActionResult OnPost()


using LoginSystemApp.Data; {
using LoginSystemApp.Models; var hashedPassword = BitConverter.ToString(
using Microsoft.AspNetCore.Mvc; System.Security.Cryptography.SHA256.HashData(
using System.Text.Encoding.UTF8.GetBytes(Password)
Microsoft.AspNetCore.Mvc.RazorPages; )).Replace("-", "");
using System.Linq;
var user = _context.Users.FirstOrDefault(u => u.Username
public class LoginModel : PageModel == Username && u.Password == hashedPassword);
{
private readonly AppDbContext _context; if (user != null)
{
public LoginModel(AppDbContext if (user.Role == "Admin")
context) {
{ return RedirectToPage("/Admin");
_context = context; }
} else
{
[BindProperty] return RedirectToPage("/Welcome", new { username =
public string Username { get; set; } user.Username });
[BindProperty] }
public string Password { get; set; } }
public string ErrorMessage { get; set; }
ErrorMessage = "Invalid username or password.";
return Page();
}
}
@page
Step 5: Create the Admin Page @model AdminModel
<!DOCTYPE html>
<html>
<head>
<title>Admin Page</title>
</head>
• Admin Page UI (Pages/Admin.cshtml):
<body>
<h2>Welcome, Admin!</h2>
<table border="1">
<thead>
<tr>
<th>Id</th>
<th>Username</th>
<th>Role</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model.Users)
{
<tr>
<td>@user.Id</td>
<td>@user.Username</td>
<td>@user.Role</td>
</tr>
}
</tbody>
</table>
</body>
</html>
Admin Page Logic (Pages/Admin.cshtml.cs):

using LoginSystemApp.Data;
using LoginSystemApp.Models;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
using System.Linq;

public class AdminModel : PageModel


{
private readonly AppDbContext _context;

public AdminModel(AppDbContext context)


{
_context = context;
}

public List<User> Users { get; set; }

public void OnGet()


{
Users = _context.Users.ToList();
}
}
Step 6: Create the Welcome Page for Users

• Welcome Page UI (Pages/Welcome.cshtml):

@page "{username}"
@model WelcomeModel
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>Welcome, @Model.Username!</h2>
<p>This is your user account page.</p>
</body>
</html>
Welcome Page Logic (Pages/Welcome.cshtml.cs):

using Microsoft.AspNetCore.Mvc.RazorPages;

public class WelcomeModel : PageModel


{
[BindProperty(SupportsGet = true)]
public string Username { get; set; }
}
Step 7: Run the Application

• dotnet run
• in terminal
• Navigate to http://localhost:5000/Login
• Admin: Username: admin, Password: adminpassword
• User: Username: user1, Password: userpassword

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy