ASP.NET重定向到默认url以外的页面
本文关键字:url NET 重定向 默认 ASP | 更新日期: 2023-09-27 18:01:03
每次成功登录后,我都能将用户重定向到默认的url(default.aspx(页面。现在我想确保非管理员的工作人员尝试访问登录(Unauthorized.aspx(到默认页面。我使用了两个asp.net页面(Default.apsx和Unauthorized.aspx(。但问题是,当我使用管理员mary tan重定向到另一个页面(Unauthorized.apsx(而不是默认的url页面时。这是我的错误:
员工和管理人员:
点击图像
输出:
查看输出
Web.config:
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" defaultUrl="~/Default.aspx" slidingExpiration="true" timeout="20"></forms>
</authentication>
登录.aspx.cs编码:
public partial class Login : System.Web.UI.Page
{
SqlConnection conn = null;
SqlCommand cmd = null;
string connectionString = null;
string staffName = null;
string staffId = null;
string role = null;
protected void Page_Load(object sender, EventArgs e)
{
}
public bool CheckValidUser(string Username, string Password)
{
bool valid = false;
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
string sql = "SELECT * from Staff WHERE Username=@Username AND Password=@Pwd And Role=N'A' OR Role=N'S'";
try
{
conn = new SqlConnection(connectionString);
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Username", Username);
cmd.Parameters.AddWithValue("@Pwd", Password);
conn.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
staffName = dr["StaffName"].ToString();
staffId = dr["StaffId"].ToString();
role = dr["Role"].ToString();
valid = true;
}
else
{
lblOutput.Text = "There is an error logging in. Please check username or password.";
}
dr.Close();
}
catch (Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
return valid;
}
protected void tbLogin_Click(object sender, EventArgs e)
{
bool validUser = CheckValidUser(tbUsername.Text, tbPassword.Text);
if (validUser)
{
Session["StaffName"] = staffName;
FormsAuthentication.SetAuthCookie(staffName, false);
FormsAuthentication.RedirectFromLoginPage(staffName, false);
Session["StaffId"] = staffId;
FormsAuthentication.SetAuthCookie(staffId, false);
FormsAuthentication.RedirectFromLoginPage(staffId, false);
Session["Role"] = role;
FormsAuthentication.SetAuthCookie(role, true);
Response.Redirect("~/Unauthorized.aspx");
}
else
{
lblOutput.Text = "Invalid User. Please try again.";
}
}
}
问题是在登录代码期间,您总是将有效用户重定向到未经授权的页面
Response.Redirect("~/Unauthorized.aspx");
如果用户处于某个角色(并确保使用ASP.NET Identity Roles system
锁定该页面(,我只需在此处插入if
语句即可重定向到正确的页面