Question

I have 4 roles in AspNetMembership Database

 Admin
 User
 Dealer
 Operator

I want to

Admin users go to Admin/Admin.aspx,

User users go to User/User.aspx,

Dealer users go to Dealer/Dealer.aspx,

Operator users go to Operator/Operator.aspx after Login.

How can I do ?

My Login.aspx.cs

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

    {

    }

    protected void btnLogin_Click(object sender, EventArgs e) 

    {
        if (Membership.ValidateUser(tbUserName.Text, tbPassword.Text))
        {
            if(string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))

            {


                FormsAuthentication.SetAuthCookie(tbUserName.Text, false);

            }




            else
                FormsAuthentication.RedirectFromLoginPage(tbUserName.Text, false);
        }

        else {
            tbUserName.ErrorText = "Invalid user";
            tbUserName.IsValid = false;
           }
       }
   }
}
Was it helpful?

Solution

The simplest way, though probably not the ideal way, would be to perform a check during the redirect. I would set up your roles as constants or an enumerable somewhere, then conditionally check:

if(string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
{
    FormsAuthentication.SetAuthCookie(tbUserName.Text, false);

    if (HttpContext.Current.User.IsInRole(ADMIN))
    {
        Response.Redirect(ADMIN_URL, true);
    }
    else if (HttpContext.Current.User.IsInRole(USER))
    {
        Response.Redirect(USER_URL, true);
    }
    else if (HttpContext.Current.User.IsInRole(DEALER))
    {
        Response.Redirect(DEALER_URL, true);
    }
    else if (HttpContext.Current.User.IsInRole(OPERATOR))
    {
        Response.Redirect(OPERATOR_URL, true);
    }
    else
    {
        Response.Redirect(SOME_DEFAULT_URL, true);
    }
}
else
{
    FormsAuthentication.RedirectFromLoginPage(tbUserName.Text, false);
}

Conceivably this check would be abstracted into a method in a library or even later within this class. This method would perform a redirect based on the first encountered role, so if a user had multiple roles (e.g. DEALER/OPERATOR) the first would take precedence.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top