使用 C# 创建 ASP.Net MVC Web 应用程序,详细信息如下:

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

如何保存用户上次登录的历史记录并在用户登录后立即显示。 (例如;上次登录时间:2021 年 5 月 31 日,星期一)

我对如何显示它感到困惑,我在这里分享我的详细信息,我们将不胜感激。

控制器登录码

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 用于 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; }
    }
}

用户验证(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;
}

登录视图:

@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>

数据库(UserProfile table):

首先,我建议使用 ASP.NET Identity (https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-5.0&tabs=visual-studio),因为它可以减轻您的工作负担,并使您的身份验证在默认情况下是安全的(切勿以明文形式存储您的密码,并且请使用参数化查询使您的 SQL 不易被注入,您的代码会受到这两种情况的影响!)。

要回答您的问题:您应该创建一个数据库 属性 来捕获上次登录,在用户登录时更新行(使用当前日期和时间),并且 return 属性 到你的控制器。然后您的控制器可以在您的视图中设置数据,并且在您的视图中您可以显示 属性.

您可以尝试使用HttpCookie来存储用户上次登录信息。

这里有一个代码示例,您可以参考:

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);
        }

结果: