Asp.NET 多层登陆实现代码

本文将详细讲解如何利用 Asp.NET 实现多层登陆,以下是完整的实现攻略:

第一步:创建用户数据库

在创建用户数据库之前,必须先安装 Microsoft SQL Server 数据库并创建一个新的数据库。可以按照以下步骤创建一个新的用户数据库:

  1. 打开 Microsoft SQL Server 的管理工具(如SqlServer Management Studio或Visual Studio)并登录
  2. 在 "Object Explorer" 窗口中,右键单击 "Databases" 文件夹,并选择 "New Database"
  3. 在 "New Database" 对话框中,输入一个数据库名称,例如 "Users",并点击 "OK" 按钮
  4. 在左侧导航栏中,展开新创建的 "Users" 数据库,右键单击 "Tables" 文件夹,并选择 "New Table"
  5. 添加一个 "Users" 表格,包括以下字段:
  6. Id:int类型,自增主键
  7. UserName:nvarchar(50),用于存放用户名
  8. Password:nvarchar(50),用于存放加密后的密码
  9. Role:nvarchar(50),用于存放用户角色
  10. 保存并关闭 "New Table" 对话框
  11. 在 "Users" 表格中,添加至少一个用户,用于后续测试验证登陆功能

第二步:创建 Asp.NET 应用程序

  1. 打开 Visual Studio,建立一个新的 Asp.NET 项目。选择类型为 "Web Application",并选择 "Empty" 模板
  2. 将项目命名为 "AspNetMultyLayerLogin"
  3. 在解决方案资源管理器中,右键单击 "AspNetMultyLayerLogin" 项目,并选择 "Add" -> "New Folder"
  4. 将新创建的文件夹命名为 "Models"
  5. 在 "Models" 文件夹中,创建一个名为 "User" 的新类,并定义以下属性:
public class User
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Role { get; set; }
}
  1. 在 "Models" 文件夹中,创建一个名为 "UserDataAccessLayer" 的新类,并定义以下方法:
public class UserDataAccessLayer
{
    private static string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    public static User GetUser(string userName, string password)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            SqlCommand command = new SqlCommand("SELECT * FROM Users WHERE UserName = @UserName AND Password = @Password", connection);
            command.Parameters.AddWithValue("@UserName", userName);
            command.Parameters.AddWithValue("@Password", password);
            SqlDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                User user = new User();
                while (reader.Read())
                {
                    user.Id = int.Parse(reader["Id"].ToString());
                    user.UserName = reader["UserName"].ToString();
                    user.Password = reader["Password"].ToString();
                    user.Role = reader["Role"].ToString();
                }
                return user;
            }
            else
            {
                return null;
            }
        }
    }
}
  1. 在 "Models" 文件夹中,创建一个名为 "RoleProvider" 的新类,并定义以下方法:
public class RoleProvider
{
    public static bool IsUserInRole(string userName, string role)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            SqlCommand command = new SqlCommand("SELECT Role FROM Users WHERE UserName = @UserName", connection);
            command.Parameters.AddWithValue("@UserName", userName);
            SqlDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    string userRole = reader["Role"].ToString();
                    if (userRole.Equals(role, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }
}
  1. 在 "Models" 文件夹中,创建一个名为 "Utils" 的新类,并定义以下方法:
public class Utils
{
    private static Random random = new Random();

    public static string GenerateSalt(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
    }

    public static string ComputeHash(string plainText, string salt)
    {
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);
        byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];
        for (int i = 0; i < plainTextBytes.Length; i++)
        {
            plainTextWithSaltBytes[i] = plainTextBytes[i];
        }
        for (int i = 0; i < saltBytes.Length; i++)
        {
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
        }
        HashAlgorithm algorithm = new SHA256Managed();
        byte[] hash = algorithm.ComputeHash(plainTextWithSaltBytes);
        return Convert.ToBase64String(hash);
    }
}
  1. 在 "Models" 文件夹中,创建一个名为 "LoginViewModel" 的新类,并定义以下属性:
public class LoginViewModel
{
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Role { get; set; }
    public bool RememberMe { get; set; }
}
  1. 在 "Models" 文件夹中,创建一个名为 "AccountController" 的新控制器,并使用以下代码替换默认的代码:
public class AccountController : Controller
{
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            string salt = Utils.GenerateSalt(16);
            string hashedPassword = Utils.ComputeHash(model.Password, salt);
            User user = UserDataAccessLayer.GetUser(model.UserName, hashedPassword);
            if (user != null)
            {
                FormsAuthentication.SetAuthCookie(user.UserName, model.RememberMe);
                if (RoleProvider.IsUserInRole(user.UserName, model.Role))
                {
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "You are not authorized to access this page");
                }
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();
        return RedirectToAction("Index", "Home");
    }

    private ActionResult RedirectToLocal(string returnUrl)
    {
        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        else
        {
            return RedirectToAction("Index", "Home");
        }
    }
}
  1. 在解决方案资源管理器中,右键单击 "AspNetMultyLayerLogin" 项目,并选择 "Add" -> "New Folder"
  2. 将新创建的文件夹命名为 "Views"
  3. 在 "Views" 文件夹中,创建一个名为 "Account" 的新文件夹
  4. 在 "Account" 文件夹中,创建一个名为 "Login.cshtml" 的新视图,并使用以下代码替换默认的代码:
@model AspNetMultyLayerLogin.Models.LoginViewModel
@{
    ViewBag.Title = "Log in";
}

<h2>@ViewBag.Title</h2>

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) 
{
    @Html.AntiForgeryToken()

    <div class="form-group">
        @Html.LabelFor(m => m.UserName, new { @class = "control-label" })
        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.UserName)
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "control-label" })
        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Password)
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Role, new { @class = "control-label" })
        @Html.DropDownListFor(m => m.Role, new SelectList(new List<string> { "Admin", "User" }), "-- Select Role --", new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Role)
    </div>

    <div class="form-group">
        @Html.CheckBoxFor(m => m.RememberMe)
        @Html.LabelFor(m => m.RememberMe, new { @class = "control-label" })
    </div>

    <div class="form-group">
        <input type="submit" value="Log in" class="btn btn-primary" />
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

第三步:测试并部署应用程序

  1. 运行应用程序并转到登录页面
  2. 输入先前在用户数据库中创建的用户来进行登录
  3. 以不同的角色尝试登录,应该会被授权或拒绝访问所请求的资源。

以上就是完整的 Asp.NET 多层登陆实现攻略。通过此方法,可以轻松实现多层登陆,并对不同用户进行授权或拒绝访问不同的页面。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Asp.NET 多层登陆实现代码 - Python技术站

(0)
上一篇 2023年5月31日
下一篇 2023年5月31日

相关文章

  • Unity使用DoTween实现抛物线效果

    Unity使用DoTween实现抛物线效果 简介 在游戏设计中,抛物线效果可以产生丰富的动态效果,例如投掷物品、跳跃等。DoTween是Unity中一个基于插值算法的补间动画库,可以轻松实现抛物线效果。 本文将详细介绍如何在Unity中使用DoTween实现抛物线效果,并提供两个示例演示。 环境准备 在使用DoTween前,需要先安装DoTween插件。可以…

    C# 2023年5月15日
    00
  • C# 实现winform软件最小化到系统托盘,开机自启动

    C# 实现winform软件最小化到系统托盘,开机自启动   问题描述   用户的电脑是win7系统,应用系统在用户电脑上运行时部分功能需要访问注册表,但是使用这些功能时会提示用户没有权限访问注册表。原因分析   win7及后续高版本系统对用户的权限控制比较严,就算用户的权限较高,但用户启动程序时默认还是以普通用户的权限启动,因此造成应用程序访问操作系统相关…

    C# 2023年5月11日
    00
  • C#递归算法和排列算法

    C#递归算法和排列算法 什么是递归算法? 递归算法是一种在函数中调用自身的算法。具有以下特征:- 一个问题可以被分解成几个相同的子问题;- 分解出来的子问题和原问题的解法方式一样;- 递归算法必须要有终止条件。 递归算法在程序设计中应用非常广泛,尤其在树形数据结构的遍历、图形搜索、分治法等方面都有很好的应用。 递归算法示例 下面是一个实现阶乘计算的递归算法:…

    C# 2023年6月7日
    00
  • C#向无窗口的进程发送消息

    下面是详细的讲解。 C#向无窗口的进程发送消息的完整攻略 在C#中,我们可以使用Windows API来向无窗口的进程发送消息。下面是完整的攻略。 1. 准备工作 要向无窗口的进程发送消息,我们需要知道目标进程的进程ID(PID)。可以使用Windows API中的Process.GetProcessesByName()方法获取指定名称的进程列表,然后根据需…

    C# 2023年6月6日
    00
  • C#(.net)中按字节数截取字符串最后出现乱码问题的解决

    标题:C#(.NET)中按字节数截取字符串最后出现乱码问题的解决 问题描述 在C#(.NET)中,我们经常会遇到需要按字节数来截取字符串的情况,比如截取标题等场景。然而,对于一些非ASCII字符,它们的字节数并不是1,这就导致按字节数截取字符串时会出现乱码问题。尤其是最后一个字符被截断时,更容易出现这种情况。该怎样解决这个问题呢? 解决方法 我们可以利用.N…

    C# 2023年6月8日
    00
  • C#和vb.net实现PDF 添加可视化和不可见数字签名

    C# 和 VB.net 都可以使用 iTextSharp 库来实现 PDF 文件添加数字签名。数字签名可以是可视化的,也可以是不可见的。 以下是实现 PDF 添加数字签名的完整攻略: 步骤 1:引入 iTextSharp 库 在项目中引入 iTextSharp 库。通常会从 NuGet 软件包管理器中安装该库,或者从官方网站 https://github.c…

    C# 2023年5月31日
    00
  • ASP.NET/C#中如何调用动态链接库DLL

    调用动态链接库(DLL)是在编程过程中常见的需求,本文将介绍如何在ASP.NET/C#中调用DLL文件。具体步骤如下: 第一步:在项目中添加DLL文件 将需要调用的DLL文件添加到项目中,通常可以通过以下两种方式实现: 在Visual Studio解决方案中添加现有项:右键单击要添加文件的文件夹,选择“添加现有项”,在文件对话框中选择DLL文件,单击“添加”…

    C# 2023年5月31日
    00
  • C#中Convert.ToDecimal()报错问题的解决

    下面我将详细讲解“C#中Convert.ToDecimal()报错问题的解决”的完整攻略,包含以下几个部分: 问题描述 原因分析 解决方法 示例演示 1. 问题描述 在C#中使用Convert.ToDecimal()方法将字符串转为十进制数时,有时候会遇到报错的情况,具体错误信息如下: System.FormatException: 字符串“str”格式不正…

    C# 2023年5月15日
    00
合作推广
合作推广
分享本页
返回顶部