Creating a login and logout system in ASP.NET MVC using a master page (layout), session management, and SQL Server as the database involves several steps. Below is a step-by-step guide:
Step 1: Setting Up the Project
- Create a New ASP.NET MVC Project:
- Open Visual Studio.
- Go to
File
>New
>Project
. - Select
ASP.NET Web Application
, name your project, and clickOK
. - Choose
MVC
and clickOK
.
- Add a SQL Server Database:
- Right-click on the project in the Solution Explorer.
- Click
Add
>New Item
. - Choose
SQL Server Database
, name it (e.g.,LoginDB.mdf
), and clickAdd
.
- Create User Table in the Database:
- Right-click on the database in the Solution Explorer.
- Click
Open
>Add New Table
. - Create a table with columns:
UserId (int, Primary Key, Identity)
,Username (nvarchar)
, andPassword (nvarchar)
. - Save the table as
Users
.
Step 2: Setting Up Models
- Create a Model for User:
- Right-click on the
Models
folder. - Click
Add
>Class
, name itUser.cs
, and clickAdd
- Right-click on the
C-sharp Code:
using System.ComponentModel.DataAnnotations;
public class User
{
public int UserId { get; set; }
[Required(ErrorMessage = “Username is required”)]
public string Username { get; set; }
[Required(ErrorMessage = “Password is required”)]
[DataType(DataType.Password)]
public string Password { get; set; }
}
Step 3: Create a Data Access Layer
- Create a Context Class:
- Add a class named
UserContext.cs
in theModels
folder.
- Add a class named
csharp
using System.Data.Entity;
public class UserContext : DbContext
{
public DbSet<User> Users { get; set; }
}
2. Configure the Connection String in Web.config
:
- Add the connection string inside the
<configuration>
section.
xml
<connectionStrings>
<add name=”UserContext”
connectionString=”Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=LoginDB;Integrated Security=True”
providerName=”System.Data.SqlClient” />
</connectionStrings>
Step 4: Setting Up Views
- Create the Master Layout (Shared Layout):
- Open the
_Layout.cshtml
file in theViews/Shared
folder. - Add basic HTML structure and links to login and logout actions.
- Open the
html
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href=”~/Content/Site.css” rel=”stylesheet” />
</head>
<body>
<div class=”navbar”>
<ul>
<li>@Html.ActionLink(“Home”, “Index”, “Home”)</li>
@if (Session[“Username”] != null)
{
<li>@Html.ActionLink(“Logout”, “Logout”, “Account”)</li>
}
else
{
<li>@Html.ActionLink(“Login”, “Login”, “Account”)</li>
}
</ul>
</div>
<div class=”content”>
@RenderBody()
</div>
</body>
</html>
2. Create Login View:
- Create a new folder
Account
under theViews
folder. - Right-click on the
Account
folder, clickAdd
>View
, name itLogin.cshtml
, and clickAdd
.
html
@model YourNamespace.Models.User
@using (Html.BeginForm(“Login”, “Account”, FormMethod.Post))
{
<h2>Login</h2>
@Html.ValidationSummary(true)
<div>
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username)
</div>
<div>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</div>
<button type=”submit”>Login</button>
}
Step 5: Creating the Account Controller
- Create Account Controller:
- Right-click on the
Controllers
folder. - Click
Add
>Controller
, name itAccountController
, and clickAdd
.
- Right-click on the
C#:
using System.Linq;
using System.Web.Mvc;
using YourNamespace.Models;
public class AccountController : Controller
{
private UserContext db = new UserContext();
// GET: Account/Login
public ActionResult Login()
{
return View();
}
// POST: Account/Login
[HttpPost]
public ActionResult Login(User model)
{
if (ModelState.IsValid)
{
var user = db.Users
.FirstOrDefault(u => u.Username == model.Username && u.Password == model.Password);
if (user != null)
{
Session[“Username”] = user.Username;
return RedirectToAction(“Index”, “Home”);
}
else
{
ModelState.AddModelError(“”, “Invalid Username or Password”);
}
}
return View(model);
}
// GET: Account/Logout
public ActionResult Logout()
{
Session.Clear();
return RedirectToAction(“Login”);
}
}
Step 6: Update the Home Controller and View
- Modify the Home Controller:
- Check session data to display personalized content.
C#:
public class HomeController : Controller
{
public ActionResult Index()
{
if (Session[“Username”] != null)
{
ViewBag.Message = $”Welcome, {Session[“Username”]}!”;
}
else
{
ViewBag.Message = “Welcome to the application!”;
}
return View();
}
}
2. Create Home Index View:
- Modify the
Index.cshtml
in theViews/Home
folder to display the message.
html:
<h2>@ViewBag.Message</h2>
Step 7: Run and Test the Application
- Run the Application:
- Click
Start
in Visual Studio. - Test login with credentials that exist in the database.
- Verify that sessions are handled correctly, and logout works as expected.
- Click
This guide sets up a basic login/logout system in ASP.NET MVC using session management and a SQL Server database. Let me know if you need further assistance or any clarifications!
Summary of Steps:
- Set Up Project:
- Create a new ASP.NET MVC project in Visual Studio.
- Add a SQL Server database (
LoginDB.mdf
) and create aUsers
table withUserId
,Username
, andPassword
columns.
- Create Models:
- Create a
User
model class with properties forUserId
,Username
, andPassword
. - Create a
UserContext
class to handle database connections using Entity Framework.
- Create a
- Configure Database Connection:
- Add a connection string in
Web.config
to link theUserContext
to the SQL Server database.
- Add a connection string in
- Set Up Views:
- Create a shared layout (
_Layout.cshtml
) with links for login and logout based on session status. - Create a
Login.cshtml
view in theAccount
folder to handle user login inputs.
- Create a shared layout (
- Create Account Controller:
- Implement
AccountController
withLogin
andLogout
actions:- Login Action: Validates the user and sets session data.
- Logout Action: Clears session data.
- Implement
- Modify Home Controller and Views:
- Update the
HomeController
to display personalized content if a user is logged in. - Display welcome messages based on session data in the
Index.cshtml
view.
- Update the
- Test the Application:
- Run the application, test login functionality with database credentials, and ensure sessions and logout work as intended.
This solution provides a basic framework for handling authentication in an ASP.NET MVC application via sessions and SQL Server.