简体   繁体   中英

Bind Menu based on Role Based Authorization asp.net c#

I would like to Bind my Menu based on userID.
In my Login page, I already can pass userID to Home page.
From Home page, use userID and show Menu which specific user can authorized.

Here is my Coding:

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

Below Image is SQL code: SQL Query From DB

Logic Error Menu Binding Not Correct

I believe the problem is in Home.aspx.cs.
Not sure how to modify Parent Child Coding Kindly Advise & Thanks.

You seem to be storing the UserID in Session State. In the other page you can read that value from the session stage and use it:

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

You should also lookup on inbuilt asp.net Authorization and Authentication as that is much more complete and secure then implementing your own.

You are loading the Menu in a recursive call. I think you are trying to get the parent menu and then load all the children menu items for the parent menu item and at the same time filter them if the user doesn't have access to them.

You need to update your GetData(int userID) function to GetData(int menuItemParentID, int userID) as you are passing menuID for userID in your code when you invoke the function recursively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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