Asp.net正确的授权消息

时间:2011-04-06 15:13:55

标签: asp.net web-config forms-authentication

这些是web.config中的设置:

<location path="Salary.aspx"> 
    <system.web> 
        <authorization>
            <allow roles="Salary Admin" /> 
            <deny users="*"/> 
        </authorization>
    </system.web> 
</location>

web.config中,这工作得非常好,但是,我想向用户显示一条适当的消息,表明他未获得授权,并提供一个返回的链接。相反,它会直接进入登录表单,我该如何解决?任何帮助将不胜感激。

btnlogin代码

protected void btnLogin_Click(object sender, EventArgs e)
        {
            bool bCheckUser;
            try
            {
               if ((txtUserName.Text == "") || (txtPassword.Text == ""))
                {
                    lblError.Visible = true;
                    lblError.ForeColor = System.Drawing.Color.Red;
                    lblError.Text = "Enter UserName and Password";
                }


                    {
                        bCheckUser = Membership.ValidateUser(txtUserName.Text, txtPassword.Text);
                        FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
                          FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text);
                        if (bCheckUser == true)
                        {
                            lblError.Visible = false;
                            Response.Redirect("MainMenu.aspx");
                        }
                        else
                        {
                            lblError.Visible = true;
                            lblError.ForeColor = System.Drawing.Color.Red;
                            lblError.Text = "You Username or Password is Invalid. Please try Again";
                        }

                }

            }
            catch(Exception ex)
            {
                lblError.Text = ex.Message.ToString();
            }
        }

加载

  protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Page.User.Identity.IsAuthenticated && !string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))                   
                    Response.Redirect("Unauthorized.aspx");
            }

        }

每当它将Page.User.Identity.IsAuthenticated视为false时,如果我在开始时将一个页面跳转到另一个页面,则表示为true,则返回false。

2 个答案:

答案 0 :(得分:0)

更好地在urp表中创建一个字段,如user_type,并修改正在验证登录部分的函数

   if(user_type.ToString()=="admin")
       {
             //do other authentication stuff
       }
   else
       {
             Response.Redirect("urerrorpage.aspx");
       }

答案 1 :(得分:0)

<location path="Salary.aspx"> 
    <system.web> 
        <authorization>
            <allow roles="Salary,Admin" /> 
            <deny users="*"/> 
        </authorization>
    </system.web> 
</location>
there should be comma in allow roles tag