Login Form with Session in ASP.NET MVC


On the Visual Studio, create new ASP.NET MVC Web Application project

Select Empty Template and Core Reference is MVC




In Controllers folder, create new controller named ProductController.cs as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LearnASPNETMVCWithRealApps.Models;

namespace LearnASPNETMVCWithRealApps.Controllers
{
    public class AccountController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(string username, string password)
        {
            if (username.Equals("acc1") && password.Equals("123"))
            {
                Session["username"] = "username";
                return View("Success");
            }
            else
            {
                ViewBag.error = "Invalid Account";
                return View("Index");
            }
        }

        [HttpGet]
        public ActionResult Logout()
        {
            Session.Remove("username");
            return RedirectToAction("Index");
        }

    }
}

In Views/Product folder, create new razor views as below:

Create new view named Index.cshtml as below:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Login Page</h3>
    @ViewBag.error
    <form method="post" action="@Url.Action("Login", "Account")">
        <table border="0" cellpadding="2" cellspacing="2">
            <tr>
                <td>Username</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" value="Login"></td>
            </tr>
        </table>
    </form>

</body>
</html>

Create new view named Success.cshtml as below:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Success</title>
</head>
<body>

    <h3>Success Page</h3>
    Welcome @Session["username"]
    <br>
    <a href="@Url.Action("Logout", "Account")">Logout</a>

</body>
</html>




Access Index action in Account controller with following url: http://localhost:9596/Account/Index

Output

Test with invalid account is username: acc2 and password: 123

Output

Test with valid account is username: acc1 and password: 123.

Output

Click logout link from success page to remove session and open login page again

Output

I recommend you refer to the books below to learn more about the knowledge in this article: