我在登录之后遇到了redirecton的问题。 基本上我要做的是当用户输入他的userName和他的登录,在表中查询搜索,并检索适当的角色,并根据该角色,它将用户重定向到他的特定文件夹。 我正在尝试这段代码
private void imgBtnLogin_Click(object sender, ImageClickEventArgs e)
{
FormsAuthentication.Initialize();
SqlConnection con = new SqlConnection("data source=.; initial catalog = AxaStock; integrated security = true");
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select r.nomRole from Collaborateur c, Role r where r.idRole=c.idRole and matricule=@matricule and password=@password";
cmd.Parameters.Add("@matricule", SqlDbType.VarChar, 64).Value = txtLogin.Text;
cmd.Parameters.Add("@password", SqlDbType.VarChar, 128).Value = txtPassword.Text;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, txtLogin.Text,
DateTime.Now,
DateTime.Now.AddMinutes(30),
true,
reader.GetString(0),
FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null)
{
returnUrl = "/";
}
}
else
{
lblError.Text = "Matricule / mot de passe incorrect. Réssayez !";
lblError.Visible = true;
}
reader.Close();
con.Close();
}
我的网站.Config
<system.web>
<authentication mode="Forms">
<forms name=".ASPXFORMSAUTH" loginUrl="Login.aspx" protection="All" path="/"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
<location path="TP">
<system.web>
<authorization>
<allow roles="Technicien de proximité"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="CDP">
<system.web>
<authorization>
<allow roles="Chef de projet"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
当我点击登录按钮时,它不会将我重定向到特定文件夹,它会在登录页面中保留,而不会给我任何消息。如何重定向到TP / Accueil.aspx? 请帮忙
答案 0 :(得分:0)
您不会在代码中的任何位置重定向。您的代码验证用户身份。将其信息存储到cookie中。试试这个
if (reader.Read())
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, txtLogin.Text,
DateTime.Now,
DateTime.Now.AddMinutes(30),
true,
reader.GetString(0),
FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
string returnUrl = Request.QueryString["ReturnUrl"];
FormsAuthentication.RedirectFromLoginPage(txtLogin.Text, false);
if (returnUrl == null)
{
returnUrl = "/";
}
}
也在您的Web.Config
中。将其添加到<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx" name="logck">
</forms>
</authentication>
来自msdn
网址http://www.contoso.com/login.aspx?ReturnUrl=caller.aspx中的, RedirectFromLoginPage方法重定向到返回URL caller.aspx。如果ReturnURL变量不存在,则 RedirectFromLoginPage方法重定向到DefaultUrl中的URL 属性。 将所需的url设置为return url参数。 欲了解更多信息,请阅读RedirectFromLoginPage.