login system without using ASP.NET Identity

  Kiến thức lập trình

Step 1: Create an ASP.NET MVC Project
Open Visual Studio and create a new ASP.NET MVC project.

Step 2: Define the User Model
Create a model class for the user. This will represent the structure of user data.

// User.cs
public class User
{
    public string Username { get; set; }
    public string Password { get; set; }
}
Step 3: Create the Account Controller
Add a controller to handle user actions like registration, login, and logout.


// AccountController.cs
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

public class AccountController : Controller
{
    private const string FilePath = "users.json";

    public ActionResult Register()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Register(User user)
    {
        var users = LoadUsers();
        users.Add(user);
        SaveUsers(users);
        return RedirectToAction("Login");
    }

    public ActionResult Login()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Login(User user)
    {
        var users = LoadUsers();
        var matchedUser = users.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password);
        if (matchedUser != null)
        {
            TempData["Username"] = matchedUser.Username;
            return RedirectToAction("Index", "Home");
        }
        ModelState.AddModelError("", "Invalid username or password");
        return View();
    }

    public ActionResult Logout()
    {
        TempData.Remove("Username");
        return RedirectToAction("Index", "Home");
    }

    private List<User> LoadUsers()
    {
        if (System.IO.File.Exists(FilePath))
        {
            var json = System.IO.File.ReadAllText(FilePath);
            return JsonConvert.DeserializeObject<List<User>>(json) ?? new List<User>();
        }
        return new List<User>();
    }

    private void SaveUsers(List<User> users)
    {
        var json = JsonConvert.SerializeObject(users);
        System.IO.File.WriteAllText(FilePath, json);
    }
}

Step 4: Create Views
Create views for the registration and login forms.
Register.cshtml

@model User

@using (Html.BeginForm())
{
    @Html.LabelFor(m => m.Username)
    @Html.TextBoxFor(m => m.Username)
    <br />
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password)
    <br />
    <input type="submit" value="Register" />
}
Login.cshtml
html
Copy code
@model User

@using (Html.BeginForm())
{
    @Html.LabelFor(m => m.Username)
    @Html.TextBoxFor(m => m.Username)
    <br />
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password)
    <br />
    <input type="submit" value="Login" />
}

Step 5: Modify the Layout View
Modify the layout view (_Layout.cshtml) to display the username in the navigation bar.

<nav>
    <ul>
        <li>@Html.ActionLink("Home", "Index", "Home")</li>
        @if (TempData["Username"] != null)
        {
            <li>Hello, @TempData["Username"].ToString()</li>
            <li>@Html.ActionLink("Logout", "Logout", "Account")</li>
        }
        else
        {
            <li>@Html.ActionLink("Login", "Login", "Account")</li>
            <li>@Html.ActionLink("Register", "Register", "Account")</li>
        }
    </ul>
</nav>

Step 6: Handle JSON Serialization/Deserialization
Install the Newtonsoft.Json package via NuGet if not already installed.

Step 7: Set up Routes
Ensure your routes are properly configured in RouteConfig.cs or using attribute routing.

That’s it! You’ve now created a simple login system without using ASP.NET Identity, including user registration, login, and logout functionality. The username of the logged-in user will be displayed in the navigation bar. Make sure to handle session expiration and other security concerns in a production environment.

New contributor

Bob Boby is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

LEAVE A COMMENT