繁体   English   中英

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

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

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

我对如何显示它感到困惑的一件事,我在这里分享我的详细信息,任何帮助将不胜感激。

Controller 登录码

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

LoginController中使用的LoginViewModel

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

验证用户(类):

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表):

在此处输入图像描述

您可以尝试使用 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);
        }

结果:

在此处输入图像描述

首先,我建议使用 ASP.NET Identity ( https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-5.0&tabs=visual-studio )默认情况下,让您的身份验证安全(永远不要以明文形式存储您的密码,请使用参数化查询使您的 SQL 不易被注入,您的代码会同时受到这两种情况的影响。)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM