Pages

Wednesday, 25 July 2012

How to redirect users to certain page based or username or user role


Step 1:
You need to setup default as intermidiate page. I have called it as Transfer.aspx

<authentication mode="Forms">
  <forms
    loginUrl="~/Login.aspx"
    defaultUrl="~/Transfer.aspx" />
</authentication>
Step 2:
Then please consider setup role based authenticaiton to relevent folders,

  <location path="Admin">
    <system.web>
      <authorization>
        <allow roles="Admin"/>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>
  <location path="Members">
    <system.web>
      <authorization>
        <allow roles="Member"/>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>
In the tranfer aspx page.
Point 1:  If you need a just perticular user, to redirect to a certain page, you can simple use user's name.
Transfer.aspx

<%@ Page Language="C#" %>
<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        if (this.Page.User != null && this.Page.User.Identity.IsAuthenticated)
        {
            if (this.Page.User.Identity.Name.Equals("Admin"))
                this.Response.Redirect("~/Admin/Default.aspx");
            else
                this.Response.Redirect("~/Member/Default.aspx");
        }
        else this.Response.Redirect("~/Login.aspx");
    }
</script>
Point 2:  If you need grop of users (role based) to redirect to a certain page,
Transfer.aspx

<%@ Page Language="C#" %>
<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        if (this.Page.User != null && this.Page.User.Identity.IsAuthenticated)
        {
            if (this.Page.User.IsInRole("Admin"))
                this.Response.Redirect("~/Admin/Default.aspx");
            else if (this.Page.User.IsInRole("Member"))
                this.Response.Redirect("~/Member/Default.aspx");
            else
                this.Response.Redirect("~/Default.aspx");
        }
        else this.Response.Redirect("~/Login.aspx");
    }
</script>

No comments:

Post a Comment