Creating ASP.Net MVC Web Application in C# with details below:

285 Views Asked by At

How to save history of user last login and display right after when user login. (e.g.; LastLogin: Monday May 31, 2021)

The one thing in which I am confused about like how to display it and I am sharing my details here any help will be appreciated.

Controller login code

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

[HttpPost]
public ActionResult Login(LoginViewModel login)
{
        if (ModelState.IsValid)
        {
            if (new UserEntity().IsValidUser(login.EmailId, login.Password))
            {
                /*Very Much important line of code, now we can use this session
                variable in Emloyee control and only valid user can access employee
                data otherwise we will redirect the user to login page in case of null
                session */
                Session["login"] = login;
                //Redirect to Employee Controller after Validation
                return RedirectToAction("Index", "Employee");
            }
            else
            {
                ViewBag.InvalidUser = "Invalid User Name or Password";
                return View(login);
            }
        }
        return View(login);
}

public ActionResult Logout()
{
    Session["login"] = null;
    Session.Abandon();
    return RedirectToAction("Login");
}

LoginViewModel used in LoginController:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Project_Login.Models
{
    public class LoginViewModel
    {
        [Display(Name = "Email Address")]
        [Required]
        public string EmailId { get; set; }
        [Display(Name = "Password")]
        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }
}

Validation for user (class):

public Boolean IsValidUser(string emailId, string password)
{
        Boolean isValid = false;

        try
        {
            string ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
            sqlConnection = new SqlConnection(ConnectionString);
            string query = @"Select * from UserProfile where EmailID='" + emailId + "' and Password = '" + password + "'";
            cmd = new SqlCommand(query, sqlConnection);
            sqlConnection.Open();
            SqlDataReader dataReader = cmd.ExecuteReader();

            if (dataReader.Read())
            {
                isValid = true;
            }
        }
        catch (Exception exp)
        {
            //exception logging
        }

        return isValid;
}

Login view:

@model Project_Login.Models.LoginViewModel
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Login</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <div class="form-horizontal">
            <h4>Login</h4>
            <hr />
            @if (ViewBag.InvalidUser != null)
            {
                <p class="alert-danger"> @ViewBag.InvalidUser </p>
            }
            <div class="form-group">
                @Html.LabelFor(model => model.EmailId, htmlAttributes:
               new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.EmailId, new {
                   htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.EmailId,
                   "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Password,
               htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Password, new {
                   htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model =>
                   model.Password, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Login" class="btn btndefault" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Not Registered? Click to Signup", "Signup")
    </div>
</body>
</html>

Database (UserProfile table):

enter image description here

2

There are 2 best solutions below

0
Jack J Jun On BEST ANSWER

You can try to to use HttpCookie to store user last login information.

Here is a code example you can refer to:

public ActionResult Login()
        {
            var username = Request.Cookies["UserName"] == null ? "" : Request.Cookies["UserName"].Value.ToString();
            
            var time = Request.Cookies["Time"] == null ? "" : Request.Cookies["Time"].Value.ToString();
            string message = string.Format("The Last login user is {0} and time is {1}", username, time);
            Response.Write(message);
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel login)
        {
            
            if (ModelState.IsValid)
            {
              
                if (IsValidUser(login.EmailId, login.Password))
                {
                    /*Very Much important line of code, now we can use this session
                    variable in Emloyee control and only valid user can access employee
                    data otherwise we will redirect the user to login page in case of null
                    session */
                    //Session["login"] = login;
                    HttpCookie cookie1 = new HttpCookie("UserName");
                    cookie1.Value = login.EmailId;
                    Response.AppendCookie(cookie1);

                    HttpCookie cookie2 = new HttpCookie("Time");
                    cookie2.Value = DateTime.Now.ToString();
                    Response.AppendCookie(cookie2);
                    ViewBag.InvalidUser = "Correct User Name or Password";

                    string message = string.Format("The Last login user is {0} and time is {1}", cookie1.Value, cookie2.Value);
                    Response.Write(message);

                }
                else
                {
                    ViewBag.InvalidUser = "Invalid User Name or Password";
                    return View(login);
                }
            }
            return View(login);
        }

Result:

enter image description here

1
T. van Schagen On

First and foremost, I would suggest using ASP.NET Identity (https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-5.0&tabs=visual-studio) as it can take work out of your hands and make your authentication secure by default (never store your passwords in plaintext and please use parameterized queries to make your SQL not prone to injection, your code suffers from both of these!).

To answer your question: you should create a database property which captures the last login, update the row at the moment the user logs in (with the current date and time), and return the property to your controller. Your controller can then set the data in your view, and in your view you can display the property.