【问题标题】:Bind Menu based on Role Based Authorization asp.net c#基于角色授权的绑定菜单asp.net c#
【发布时间】:2019-07-25 07:48:42
【问题描述】:

我想根据用户 ID 绑定我的菜单。
在我的 Login 页面中,我已经可以将 userID 传递到 Home 页面。
首页 页面,使用 userID 并显示特定用户可以授权的菜单。

这是我的编码:

登录.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace OT_WorkFlow_Application
{
   public partial class Login : System.Web.UI.Page
{
    //string strqry, User, Password;
    String User, Password;
    String UserID;
    String UserType;
    int RowCount;

    protected void Page_Load(object sender, EventArgs e)
    {
        lblErrorMessage.Visible = false;
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        using (SqlConnection sqlCon = new SqlConnection(@"Mysql connection;"))
        {

            using (SqlCommand cmd = new SqlCommand("sp_CheckUser", sqlCon))
            {
                using (SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, sqlCon))
                {
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    RowCount = dt.Rows.Count;
                    for (int i = 0; i < RowCount; i++)
                    {

                        User = dt.Rows[i]["UserName"].ToString();
                        Password = dt.Rows[i]["Password"].ToString();                            
                        UserID = dt.Rows[i]["UserID"].ToString();

                        if (User == txtUserName.Text && Password == txtPassword.Text)
                        {

                            Session["UserName"] = User;
                            Session["UserID"] = UserID;                               
                            Response.Redirect("Home.aspx");

                        }
                        else
                        {
                            lblErrorMessage.Visible = true;
                        }
                    }
                }
            }
        }

      }
   }
}

Home.aspx.cs

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.IO;
 using System.Data.SqlClient;
 using System.Data;
 using System.Configuration;


 namespace OT_WorkFlow_Application
 {
    public partial class OT : System.Web.UI.MasterPage
   {

   SqlConnection sqlCon = new SqlConnection(@"Mysql connection;");


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = this.GetData(0);
            PopulateMenu(dt, 0, null);
        }

    }       
    private DataTable GetData(int UserID)
    {
        //Sql query for testing purpose           
        string query = "select m.* from tbpermission as per , [tbrolemodule] as rm, [tbrole] as r, [tbmodule] m, [tblUser] u where per.RoleID = rm.RoleID and rm.RoleID = r.RoleID and rm.moduleID = m.moduleID and per.Userid = u.Userid";

        string LoginDBConnectionString1 = ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString;
         using (SqlConnection con = new SqlConnection(LoginDBConnectionString1))

        {
            DataTable dt = new DataTable();
            //using (SqlCommand cmd = new SqlCommand("Sp_Module", sqlCon))
            using (SqlCommand cmd = new SqlCommand(query))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {

                    cmd.Parameters.AddWithValue("@UserID", UserID);
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                }
            }
            return dt;
        }
    }


    private void PopulateMenu(DataTable dt, int UserID, MenuItem parentMenuItem)
    {
        string currentPage = Path.GetFileName(Request.Url.AbsolutePath);
        foreach (DataRow row in dt.Rows)
        {
            MenuItem menuItem = new MenuItem
            {

                //Value = row["UserID"].ToString();
                Value = row["ModuleID"].ToString(),
                Text = row["Name"].ToString(),
                //Text1 = row["Description"].ToString(),
                NavigateUrl = row["Url"].ToString(),
                Selected = row["Url"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
            };

            if (UserID == 0  )
            {
                Menu1.Items.Add(menuItem);
                DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
                PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
            }
            else
            {
                parentMenuItem.ChildItems.Add(menuItem);
            }
          }
       }
     }
   }

下图是SQL代码: SQL Query From DB

逻辑错误 Menu Binding Not Correct

我相信问题出在 Home.aspx.cs。
不知道如何修改父子编码 请多多指教,谢谢。

【问题讨论】:

    标签: c# asp.net data-binding user-roles role-base-authorization


    【解决方案1】:

    您似乎将UserID 存储在会话状态中。在另一个页面中,您可以从会话阶段读取该值并使用它:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            int UserID = 0;
            if(Session["UserName"] != null) int.TryParse(Session["UserName"].ToString(), out UserID);                                             
            DataTable dt = this.GetData(UserID);
            PopulateMenu(dt, UserID, null);
        }
    }
    

    您还应该查找内置的 asp.net 授权和身份验证,因为这比实现您自己的更加完整和安全。

    【讨论】:

    • 我在调试时得到 UserID = 0。似乎它不是从 Session UserID 中获取的
    • 那么你需要调试代码存储在Session状态的问题。
    【解决方案2】:

    您正在递归调用中加载菜单。我认为您正在尝试获取父菜单,然后为父菜单项加载所有子菜单项,同时在用户无权访问它们时过滤它们。

    当您递归调用函数时,您需要将 GetData(int userID) 函数更新为 GetData(int menuItemParentID, int userID),因为您在代码中为 userID 传递 menuID。

    【讨论】:

    • 是的逻辑将是为什么但我会在 DataTable tb = this.GetData(0);说“没有对应于'OT.GetData(int,int)'的所需形参'ParentModuleID'的参数
    猜你喜欢
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2013-04-11
    • 2012-05-14
    • 1970-01-01
    相关资源
    最近更新 更多