Search code examples
c#asp.netvisual-studio-2010roleproviderlogin-control

Can't Detect User Role


Using asp.net and c# and visual studio 2010 I have a login page and a login control in it and i'm doing something that when a user try's to login , it will detect the user role. Here's my code :

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

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Login1_LoggedIn(object sender, EventArgs e)
    {
        if (Session["Admin"] != null)
        {
            Response.Redirect("~/Admin/HomeAdmin.aspx");
        }
        else if (Session["Professor"] != null)
        {
            Response.Redirect("~/Professor/HomeProfessor.aspx");
        }
        else if (Session["Student"] != null)
        {
            Response.Redirect("~/Student/HomeStudent.aspx");
        }            
    }

    protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
    {
        if (Roles.IsUserInRole("Administor"))
        {
            Session["Admin"] = Login1.UserName;
            //only run for admins
        }




        else if (Roles.IsUserInRole("Professor"))
        {
            Session["Professor"] = Login1.UserName;
            //only run for professors
        }





        else if (Roles.IsUserInRole("Student"))
        {
            Session["Student"] = Login1.UserName;
            //only run for students
        }
    }
}  

Then when i login it will detect the wrong role for example i login with a Admin user but it will detect it as a Student! And as you see in the code it will redirect me to the page (HomeStudent.aspx).

Here's a view of my role manager:Click here to see the image of my role manager

What do you think is the problem and what should i do?!!


Solution

  • I found the solution and solved my problem by changing codes to this :

     if (Roles.IsUserInRole(Login1.UserName , "Administor"))
        {
            Session["Admin"] = Login1.UserName;
            Response.Redirect("~/Admin/HomeAdmin.aspx");       
            //only run for admins
    
        }
    
    
        else if (Roles.IsUserInRole(Login1.UserName , "Professor"))
        {
            Session["Professor"] = Login1.UserName;
            Response.Redirect("~/Professor/HomeProfessor.aspx");
            //only run for professors
        }
    
    
    
        else if (Roles.IsUserInRole(Login1.UserName , "Student"))
        {
            Session["Student"] = Login1.UserName;
            Response.Redirect("~/Student/HomeStudent.aspx"); 
            //only run for students
        }