ASP.NET Core(.NET Framework)实现用户与管理员登录后显示不同导航栏
基于角色的动态导航栏实现方案(ASP.NET Web Forms + SQL Server)
开发环境与需求
- 开发栈:ASP.NET Web Forms(.NET Framework)、C#、SQL Server
- 需求要点:
- 登录后根据用户/管理员角色,在MainPage展示对应导航栏项
- 导航栏配置存储于数据库,增改后页面实时生效
现有代码
Login页面(Login.aspx.cs)
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; namespace WebApplication2 { public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void LoginBtn_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;Initial Catalog=Users;Integrated Security=True"); con.Open(); string query = "SELECT username, password FROM UsersRole WHERE username = '" + TxTUser.Text + "' and password = '" + TxTPass.Text + "'"; SqlCommand cmd = new SqlCommand(query, con); SqlDataReader sdr = cmd.ExecuteReader(); if (sdr.Read()) { LabelMSG.Text = "You have Successfully Logged in!"; Response.Redirect("MainPage.aspx"); } else { LabelMSG.Text = "Please Check your username or password!"; } con.Close(); } } }
MainPage页面(MainPage.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="WebApplication2.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <nav> <ul> <li id="item1"><a href="#">Accounting</a></li> <li id="item2"><a href="#">IT</a></li> <li id="item3"><a href="#">Policies</a></li> <li id="item4"><a href="#">Sales</a></li> <li id="item5"><a href="#">Marketing</a></li> <li id="item6"><a href="#">Equipment</a></li> <li id="item7"><a href="#">Transportation</a></li> <li id="item8"><a href="#">Printer</a></li> <li id="item9"><a href="#">Cashier</a></li> <li id="item10"><a href="#">HR</a></li> </ul> </nav> </body> </html>
解决方案步骤
1. 数据库表设计
创建导航项与角色关联的核心表,同时扩展原有用户表:
-- 角色表 CREATE TABLE Roles ( RoleId INT PRIMARY KEY IDENTITY(1,1), RoleName VARCHAR(50) NOT NULL UNIQUE -- 示例值:'User', 'Admin' ) -- 导航项表 CREATE TABLE NavigationItems ( NavId INT PRIMARY KEY IDENTITY(1,1), NavText VARCHAR(50) NOT NULL, -- 导航显示文本 NavUrl VARCHAR(200) NOT NULL, -- 跳转链接 IsActive BIT DEFAULT 1 -- 是否启用该导航项 ) -- 角色-导航映射表(控制不同角色可见的导航项) CREATE TABLE RoleNavigationMapping ( MappingId INT PRIMARY KEY IDENTITY(1,1), RoleId INT FOREIGN KEY REFERENCES Roles(RoleId), NavId INT FOREIGN KEY REFERENCES NavigationItems(NavId), UNIQUE(RoleId, NavId) -- 避免重复映射 ) -- 扩展原有UsersRole表,添加角色关联字段 ALTER TABLE UsersRole ADD RoleId INT FOREIGN KEY REFERENCES Roles(RoleId) NOT NULL
2. 修复Login页面并存储用户角色
修复原代码的SQL注入风险,同时登录时获取用户角色并存入Session:
using System; using System.Data.SqlClient; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication2 { public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Session.Clear(); // 清除旧会话数据 } } protected void LoginBtn_Click(object sender, EventArgs e) { string connStr = "Data Source=(LocalDB)\\MSSQLLocalDB;Initial Catalog=Users;Integrated Security=True"; using (SqlConnection con = new SqlConnection(connStr)) { con.Open(); // 参数化查询避免SQL注入 string query = "SELECT ur.username, r.RoleName FROM UsersRole ur JOIN Roles r ON ur.RoleId = r.RoleId WHERE ur.username = @Username AND ur.password = @Password"; SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@Username", TxTUser.Text.Trim()); cmd.Parameters.AddWithValue("@Password", TxTPass.Text.Trim()); SqlDataReader sdr = cmd.ExecuteReader(); if (sdr.Read()) { // 存储用户身份信息到Session Session["Username"] = sdr["username"].ToString(); Session["RoleName"] = sdr["RoleName"].ToString(); LabelMSG.Text = "登录成功!"; Response.Redirect("MainPage.aspx"); } else { LabelMSG.Text = "用户名或密码错误,请检查!"; } } } } }
3. 动态生成MainPage导航栏
移除硬编码导航项,使用Repeater控件动态绑定数据库中的角色专属导航项:
MainPage.aspx修改
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="WebApplication2.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>主页</title> </head> <body> <nav> <asp:Repeater ID="NavRepeater" runat="server"> <HeaderTemplate> <ul> </HeaderTemplate> <ItemTemplate> <li><a href='<%# Eval("NavUrl") %>'><%# Eval("NavText") %></a></li> </ItemTemplate> <FooterTemplate> </ul> </FooterTemplate> </asp:Repeater> </nav> </body> </html>
MainPage.aspx.cs修改
using System; using System.Data; using System.Data.SqlClient; using System.Web.UI; namespace WebApplication2 { public partial class MainPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // 未登录则跳转回登录页 if (Session["RoleName"] == null) { Response.Redirect("Login.aspx"); return; } if (!IsPostBack) { LoadRoleNavigation(); } } private void LoadRoleNavigation() { string roleName = Session["RoleName"].ToString(); string connStr = "Data Source=(LocalDB)\\MSSQLLocalDB;Initial Catalog=Users;Integrated Security=True"; using (SqlConnection con = new SqlConnection(connStr)) { con.Open(); // 根据当前角色查询可用导航项 string query = @" SELECT ni.NavText, ni.NavUrl FROM NavigationItems ni JOIN RoleNavigationMapping rnm ON ni.NavId = rnm.NavId JOIN Roles r ON rnm.RoleId = r.RoleId WHERE r.RoleName = @RoleName AND ni.IsActive = 1 ORDER BY ni.NavId"; SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@RoleName", roleName); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); // 绑定到Repeater控件 NavRepeater.DataSource = dt; NavRepeater.DataBind(); } } } }
4. 实时生效说明
每次加载MainPage时都会直接从数据库读取最新的导航配置,因此只要在数据库中增改NavigationItems或RoleNavigationMapping表的数据,刷新页面即可看到更新后的导航栏,无需重启应用。
内容的提问来源于stack exchange,提问作者Elie
相关产品推荐
相关产品推荐

