我需要将我的用户重定向到AuthError.aspx页面(“您无权访问此页面”),以进行身份验证,但尝试访问他们无法访问的页面(由于考试的角色) 。如果我这样设置web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
这是系统的错误行为,因为用户已经通过身份验证,因此无需将其重定向到此页面。但是,如果我在此处编写AuthError.aspx而不是Login.aspx,如何将尚未通过身份验证的用户重定向到登录页面?
最佳答案
在登录页面的Page_Load上,您将要检查用户是否已通过身份验证,以及是否要将用户重定向到您的拒绝访问页面:
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated) // if the user is already logged in
{
Response.Redirect("~/AccessDenied.aspx");
}
}
如果您想了解更多,可以检查ReturnUrl参数以确定用户是否直接进入页面(例如,通过他们直接保存在登录页面上的书签)并进行不同的处理。这是一个例子:
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
// if they came to the page directly, ReturnUrl will be null.
if (String.IsNullOrEmpty(Request["ReturnUrl"]))
{
/* in that case, instead of redirecting, I hide the login
controls and instead display a message saying that are
already logged in. */
}
else
{
Response.Redirect("~/AccessDenied.aspx");
}
}
}
关于asp.net - 未经授权时如何将用户重定向到ASP.NET页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4834387/